Search code examples
phpprogramming-languages

Should a function be used in both static and object context


In my company's codebase, i see functions used in both static and object context. For e.g. a class A has a function b() which is called both using A::b() and/or object_of_type_A->b(). I know this throws an error if strict is turned on. But I wanted to know if this is a bad practice and if yes, then why? Thanks for any answers.

Let me know if I don't make sense anywhere. I would be happy to clarify.


Solution

  • Here's some test code:

    <?php
    
    error_reporting(E_ALL | E_STRICT);
    
    class Foo{
        public function a(){
        }
        public static function b(){
        }
    }
    
    $MyFoo = new Foo;
    Foo::a(); // Strict Standards: Non-static method Foo::a() should not be called statically
    Foo::b();
    $MyFoo->a();
    $MyFoo->b(); // No complaints
    
    ?>
    

    PHP/5.3 warns about static calls to non-static methods, which is fine since they are subject to failure as soon as you want to access $this. But it does not complain about object context calls to static functions: there's nothing that can go wrong. This behaviour is documented:

    Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can) [...] Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

    So, as far as PHP is concerned, what you found in the code base is not wrong. However, I think it's slightly confusing.