I thought usually we use static method because we do not need to instantiate objects. and we can use className::staticFunction
to call static method, bub today found:
<?php
class Foo {
static public function helloWorld() {
print "Hello world " ;
}
}
Foo::helloWorld();
<?php
class Foo {
public function helloWorld() {
print "Hello world " ;
}
}
Foo::helloWorld();
Question:
Both of above scripts work. We did not declare function as static
, we can still use className::staticFunction
to call the function. Why do we need use static methods?
We did not declare function as static, we can still use
className::staticFunction
What you probably didn't notice is that PHP complains about the second type of invocation:
PHP Strict Standards: Non-static method
Foo::helloWorld()
should not be called statically in php shell code on line 1Strict Standards: Non-static method
Foo::helloWorld()
should not be called statically in php shell code on line 1
To make these notices visible you need to set the value of error_reporting
to -1
, either using ini_set()
or via the php.ini
configuration file; btw, this is recommended during development.
Conclusion
A function that's called statically should be declared as static function xyz()
.
Update
Btw, using the scope resolution operator ::
doesn't necessarily mean you're making a static call; consider this example:
class Foo
{
public function helloWorld()
{
print "Hello world ";
}
public function doSomething()
{
self::helloWorld();
}
}
$f = new Foo;
$f->doSomething();
This works because using self::
as opposed to Foo::
doesn't change the invocation "mode" (unless the method you're calling is defined as static
).
The "problem" with static methods is the way they're called:
Foo::bar();
Any call to a static method is by necessity hardcoded and cannot easily be substituted. Compare with:
$foo->bar();
$foo
is a variable here, meaning the exact object and implementation of bar()
can be substituted. This is important for and the basis of dependency injection.
You'd use a static method for:
DateTime::createFromFormat()
instead of new DateTime
You may use static functions in other scenarios here and there, but these are the main points. You need to be aware that declaring a method static means you need to call it statically, which means its call-time use cannot really be altered. For a long treaty on this subject, read How Not To Kill Your Testability Using Statics.
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