dtuzjzs3853 2013-04-02 02:24
浏览 27
已采纳

非静态地调用静态方法

I came across something like this, and am not sure what to make off it. Is there any good reason to do this, or to avoid it?

class Foo {

  static public function bar() {}

}

someMethod() {

  $instanceOfFoo->bar();

}
  • 写回答

2条回答 默认 最新

  • dousui8263 2013-04-02 04:34
    关注

    The PHP documentation says:

    [...] A property declared as static can not be accessed with an instantiated class object (though a static method can). [...] Static properties cannot be accessed through the object using the arrow operator ->.

    without specifying anything special for static methods being called by ->. You should definitely avoid it though, because it causes confusion to the reader who's expecting $obj->meth() to be a non-static method and Cls::meth() a static method.

    Surprisingly this behavior is not triggering any error. The reason for this is that a static method, called by $object->method() is internally translated to className::method() at run time (with the only difference being that $this = NULL is set).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程