Home » Php » In PHP, why I am able to access non-static method in a static way?

In PHP, why I am able to access non-static method in a static way?

Posted by: admin July 12, 2020 Leave a comment

Questions:

In the following code, nonStatic() is not a static method. Even then I am able to access it without creating an object (in a static way). Could anyone please help me in understanding as this is not possible in other languages like Java?

<?php
class MyClass
{
    function nonStatic() {
        echo "This can be printed";
    }
}
MyClass::nonStatic(); // This can be printed
How to&Answers:

Not sure, probably some PHP magic (it’s a bit like that sometimes), but you shouldn’t do it.

Read more here http://php.net/manual/en/language.oop5.static.php

They also show a similar example, but note:

Calling non-static methods statically generates an E_STRICT level warning meaning this magic ability may disappear in future versions. So don’t do it 🙂

Answer:

It’s allowed, but it generates an E_STRICT warning:

Error #: 2048, Error: Non-static method MyClass::nonStatic() should not be called statically, assuming $this from incompatible context

In the earlier OO implementations of PHP this was silently allowed, but better practices have since been adopted.

The opposite works without a hitch though:

class Test
{
    function foo()
    {
        echo $this->bar();
    }

    static function bar()
    {
        return "Hello world\n";
    }
}

$x = new Test;
$x->foo();

This prints Hello world.

Answer:

It seems as though the developers of PHP didn’t see any value in disallowing static access of non-static methods. This is just one of those idiosyncratic features of PHP that doesn’t really serve a purpose. It certainly is bad programming practice to call a non-static method statically, but in PHP it is possible. Maybe in a future version of PHP they will disallow this, but for now, it’s just part of the language.

Edit:

Thankfully, the opposite is not allowed – you cannot call a static method from an object context. As Jack pointed out below, you can call a static method from an object context – hardly a best practice in the OOP paradigm, but it’s allowed.