I'm not pro in Object Oriented Programming and I got a silly question:
class test {
public static function doSomething($arg) {
$foo = 'I ate your ' . $arg;
return $foo;
}
}
So the correct way to call doSomething()
method is to do test::doSomething('Pizza');
, Am I right?
Now, what will happen if I call it like this:
$test = new test;
$bar = $test->doSomething('Sandwich');
I've tested it and it's working without any error or notice or etc. but is that correct to do this?
It is better you call it this way to avoid
E_STRICT
on some version of PHPFROM PHP DOC
Also
It makes no difference if your method don't use
$this
and don't access to static properties.Static properties cannot be accessed through the object using the arrow operator ->.
$this is not available inside the method declared as static.
But, you should always use
::
to call a static method, even through php let you call it on an instance.As Baba already pointed out, it results in an
E_STRICT
depending on your configuration.But even if that's no problem for you, I think it's worth mentioning some of the pitfalls which may result from calling static methods in a non-static way.
If you have a class hierarchy like
This produces the following output:
As you can see, it's easy to achieve unexpected behaviour when mixing static and non-static method calls and techniques.
Therefore, my advice also is: Use Class::method to explicitly call the static method you mean to call. Or even better don't use static methods at all because they make your code untestable.