I thought that the use of the static
keyword in the declaration of a class function meant that you could call the function without an instance of the class using the scope resolution operator (::
).
For example:
class Foo
{
public static function static_function() {
return 'x';
}
public function non_static_function() {
return 'y';
}
}
// to call static_function:
echo Foo::static_function();
// to call non_static_function:
$foo = new Foo();
echo $foo->non_static_function();
The PHP.net documentation on static
seems to support this idea.
I came across some code yesterday that someone had wrote accessing class functions using the scope resolution operator that had NOT been defined with the static keyword. I was surprised and confused to see this worked.
Given my class defined above, Foo
, it turns out you can actually do:
echo Foo::static_function();
echo Foo::non_static_function();
Resulting in output xy
without generating any errors or warnings.
If you can access non-static class functions without the static
keyword, what is the point in it?