I am studying PHP,OOP and i am at Static, At this php.net/static i didnt understand this sentence
Calling non-static methods statically generates an E_STRICT level warning.
I did understand it's Valid for methods only (not for Properties) by the sentence above, but i didn't succeed to understand It practically, I'm glad if anything could please show me code that explains the sentence above, Wishing you a pleasant week.
class Foo
{
public static $my_static = 'foo';
public $my_non_static = 'bar';
public function staticValue() {
return self::$my_static;
}
public function nonStaticValue() {
return self::$my_non_static;
}
}
print Foo::$my_static . "\n"; // OK
print Foo::staticValue(). "\n"; // E_STRICT
print Foo::$my_non_static . "\n"; // Fatal
print Foo::nonStaticValue(). "\n"; // Fatal
print Foo::$my_static . "\n";
is OK - static property accessed statically.
print Foo::staticValue(). "\n";
gives E_STRICT - non-static method accessed statically, but not Fatal error, because this method doesn't access non-static properties.
Other two give Fatal error because non-static field cannot be accessed statically.
Here is an example of what they mean with the sentence you are asking about.
Consider the following class with one method (it is not static).
class Test
{
function method()
{
echo "Hello from method";
}
}
Test::method(); // attempt to statically call a non-static method
This is the output:
Strict Standards: Non-static method Test::method() should not be called statically in /obj.php on line 12
Hello from method
As you can see, it did execute the method when called static even though it is not a static method, however a strict error message was displayed.
If the method method()
referenced the keyword $this
, then you would encounter a fatal error because $this
does not exist in the context of a static method call. So while it is technically possible to call a non-static class method statically, it should not be done.
EDIT:
The reason you are even allowed to call a non-static class member statically is because the static keyword did not exist in PHP4 in the context of class methods so if you were designing a static class or method in PHP4, there was no keyword to indicate it, you would simply call it in the static fashion. Now PHP5 emits the warning if the method is called statically but doesn't have the static keyword in the declaration.
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