I have the following code (like, for real, this is my real code) :
<?php
class Foobar
{
public static function foo()
{
exit('foo');
}
}
When I run $foobar = new FooBar; $foobar->foo()
it displays foo
.
Why would PHP try to use a static method in an object context ? Is there a way to avoid this ?
Ok you guys didn't get my problem : I know the differences between static and non static methods and how to call them. That's my whole point, if I call $foobar->foo()
, why does PHP tries to run a static method ?
Note : I run PHP 5.4.4, error reporting to E_ALL
.
We may need more information about the FooBar declaration. Obviously, you cannot declare two methods foo() even if one is a static method and the other one an instance method:
So, I suppose that you want to reach a magic
__call()
method, like so:To achieve that, look at this piece of code:
Since PHP is quite a forgiving language you could prevent this default behavior by overloading
__callStatic
and maybe use reflections to validate the method scope.http://php.net/manual/en/language.oop5.overloading.php#object.call
http://php.net/ReflectionClass
To call a static method, you don't use:
You call
The PHP manual says...
This is why you are able to call the method on an instance, even though that is not what you intended to do.
Whether or not you call a static method statically or on an instance, you cannot access
$this
in a static method.http://php.net/manual/en/language.oop5.static.php
You can check to see if you are in a static context, although I would question whether this is overkill...
One additional note - I believe that the method is always executed in a static context, even if it is called on an instance. I'm happy to be corrected on this if I'm wrong though.