Since you state that you already understand what static
means, I'll skip over that.
However, it may still be good to reference PHP's documentation on the static
keyword. In particular the following two alerts are important (and hard to glance over, really).
Caution In PHP 5, calling non-static methods statically generates an E_STRICT level warning.
And this one (italic emphasis mine).
Warning In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.
So, to cut a long story short: yes, your example will run (for now), because the PHP interpreter will try to fix up your mistake for you. You should however never do this. What the PHP interpreter will do is:
Say your $obj
is of type Foo
. Then it will read
$obj->staticMethod($para1, $para2);
conclude that staticMethod
is static
and instead execute
Foo::staticMethod($para1, $para2);
It is of course perfectly fine to pass parameters that are properties of an instance of Foo
. It doesn't matter to staticMethod
where the parameters come from.
To elaborate a bit more on why this works, while using $this
in a static
method is not allowed.
You can think of normal methods as static
functions that have one extra: they receive an implicit parameter $this
. The value of $this
is simply the object on which the method is called. Thus, $obj->do($a, $b, $c)
is equivalent to calling Foo::do($obj, $a, $b, $c)
and naming the first argument of do
, $this
. This is convenient, because we can now easily define methods that work on an instance of an object without having to explicitly state over and over again that this instance is a parameter of our methods. Great.
Now back to static
functions. The only difference with normal methods is that they do not receive this implicit $this
parameter. Thus, using $this
inside of them is invalid. Not because it is forbidden, but because it does not reference anything. PHP does not (and cannot) have a clue what $this
should refer to.
Another way to look at it. Say that our Foo
class has two properties: $para1
and $para2
, both numbers. Say that you write a method that returns the sum of these numbers. One way is to do this:
public static function sum($para1, $para2) {
return $para1 + $para2;
}
Great. Works. However, it is annoying to have to call it like this
$sum = Foo::sum($obj->para1, $obj->para2);
So, this is what methods are for!
public function sum(/* implicit $this parameter */) {
// write looking up the properties once inside the function, instead
// of having to write it every time we call the function!
return $this->para1 + $this->para2;
}
// ...
$sum = $obj->sum(); // $obj is passed implicitly as $this
Because static functions do not receive an implicit $this
parameter, using $this
inside of them is like trying to use $undefined
when you have never defined it. Thus, invalid.