Static methods in PHP

前端 未结 6 744
走了就别回头了
走了就别回头了 2020-12-15 04:38

Why in PHP you can access static method via instance of some class but not only via type name?

UPDATE: I\'m .net developer but i work with php developers too. Recent

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 05:11

    Why in PHP you can access static method via instance of some class but not only via type name?

    Unlike what you are probably used to with .NET, PHP has dynamic types. Consider:

    class Foo
    {
      static public function staticMethod() { }
    }
    
    class Bar
    {
      static public function staticMethod() { }
    }
    
    function doSomething($obj)
    {
      // What type is $obj? We don't care.
      $obj->staticMethod();
    }
    
    doSomething(new Foo());
    doSomething(new Bar());
    

    So by allowing access to static methods via the object instance, you can more easily call a static function of the same name across different types.

    Now I don't know if there is a good reason why accessing the static method via -> is allowed. PHP (5.3?) also supports:

    $obj::staticMethod();
    

    which is perhaps less confusing. When using ::, it must be a static function to avoid warnings (unlike ->, which permits either).

提交回复
热议问题