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
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With