PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I'm reading the code below from this website and came accross this explanation and example code
Essentially, all methods can be called statically in PHP5 anyway, as was possible in PHP4. However, the static keyword prevents a method declared with it from being called via an object instance, as the example demonstrates.
It says that the method that was declared static cannot be called from an object instance. Well I'm testing this code and sure enough it DOES let me call static Foo() from an object instance. I get no error. Is the example just wrong or is there a setting in the php.ini that enforces this?
Oh wait... I AM able to call the static method from an object instance. The error that is generated is when I call MyStatic::bar()... it says I shouldn't call it statically since it's not declared static. But in my original question where the article says "calling a static method from an object instance will generate an error" such as $obj->foo() is actually not causing an error. How do I prevent an object instance from calling a static method as the article suggests? Unless I'm reading it wrong...
However, the static keyword prevents a method declared with it from being called via an object instance, as the example demonstrates.
I just want to clarify because it is easy to get confused on this. The thing about statics is that they are declared so that they can only be called statically. However, that does not limit their use -- it only the syntax used to call them.
class MyStatic {
static function foo() {
$this->bar(); // NOT ok
return 'This is foo()';
}
function bar() {
MyStatic::foo(); // ok
self::foo(); // ok
return 'This is bar()';
}
}
// These are all ok
MyStatic::foo();
$obj = new MyStatic();
$obj->bar();