Is the "static" keyword necessary in PHP?
It开发者_如何学运维 seems that the uaa() function can be used as a static function even though it is not specifically defined as such. I'm wondering if using the "static" keyword is ever necessary.
<?php
class foo
{
functon uaa()
{
// do something
}
}
I'm not sure. But if you do that it triggers an E_STRICT:
Strict Standards: Non-static method a::non_static() should not be called statically in c:\file.php on line 12
It is probably wise to be explicit about what is static and what isn't, at least so you are less likely to do something like try to access $this
not in object context.
Strictly speaking, you can call a non-static function statically. You will generate an E_STRICT
error though. And if you use $this
in the method, you'll get a bigger error (I'm pretty sure it's an E_WARNING
, but it may be more significant).
The static
keyword was put in for enforcement. It's to prevent you from trying to call a static method from an instance. So while it's not strictly needed, it is good design practice to use it to identify and partially enforce the appropriate calling.
Plus, it's there to "future proof" your code. What I mean is that in later versions of PHP, they may remove the "feature" when you can call non-static methods statically (Which is why it's an E_STRICT
error now).
精彩评论