After enabling strict warnings in PHP 5.2, I saw a load of strict standards warnings from a project that was originally written without strict warnings:
Strict Standards: Static function Program::getSelectSQL() should not be abstract in Program.class.inc
The function in question belongs to an abstract parent class Program and is declared abstract static because it should be implemented in its child classes, such as TVProgram.
I did find references to this change here:
Dropped abstract static class functions. Due to an oversight, PHP 5.0.x and 5.1.x allowed abstract static functions in classes. As of PHP 5.2.x, only interfaces can have them.
My question is: can someone explain in a clear way why there shouldn't be an abstract static function in PHP?
It's a long, sad story.
When PHP 5.2 first introduced this warning, late static bindings weren't yet in the language. In case you're not familiar with late static bindings, note that code like this doesn't work the way you might expect:
<?php
abstract class ParentClass {
static function foo() {
echo "I'm gonna do bar()";
self::bar();
}
abstract static function bar();
}
class ChildClass extends ParentClass {
static function bar() {
echo "Hello, World!";
}
}
ChildClass::foo();
Leaving aside the strict mode warning, the code above doesn't work. The self::bar() call in foo() explicitly refers to the bar() method of ParentClass, even when foo() is called as a method of ChildClass. If you try to run this code with strict mode off, you'll see "PHP Fatal error: Cannot call abstract method ParentClass::bar()".
Given this, abstract static methods in PHP 5.2 were useless. The entire point of using an abstract method is that you can write code that calls the method without knowing what implementation it's going to be calling - and then provide different implementations on different child classes. But since PHP 5.2 offers no clean way to write a method of a parent class that calls a static method of the child class on which it is called, this usage of abstract static methods isn't possible. Hence any usage of abstract static in PHP 5.2 is bad code, probably inspired by a misunderstanding of how the self keyword works. It was entirely reasonable to throw a warning over this.
But then PHP 5.3 came along added in the ability to refer to the class on which a method was called via the static keyword (unlike the self keyword, which always refers to the class in which the method was defined). If you change self::bar() to static::bar() in my example above, it works fine in PHP 5.3 and above. You can read more about self vs static at New self vs. new static.
With the static keyword added, the clear argument for having abstract static throw a warning was gone. Late static bindings' main purpose was to allow methods defined in a parent class to call static methods that would be defined in child classes; allowing abstract static methods seems reasonable and consistent given the existence late static bindings.
You could still, I guess, make a case for keeping the warning. For instance, you could argue that since PHP lets you call static methods of abstract classes, in my example above (even after fixing it by replacing self with static) you're exposing a public method ParentClass::foo() which is broken and that you don't really want to expose. Using a non-static class - that is, making all the methods instance methods and making the children of ParentClass all be singletons or something - would solve this problem, since ParentClass, being abstract, can't be instantiated and so its instance methods can't be called. I think this argument is weak (because I think exposing ParentClass::foo() isn't a big deal and using singletons instead of static classes is often needlessly verbose and ugly), but you might reasonably disagree - it's a somewhat subjective call.
So based upon this argument, the PHP devs kept the warning in the language, right?
Uh, not exactly.
PHP bug report 53081, linked above, called for the warning to be dropped since the addition of the static::foo() construct had made abstract static methods reasonable and useful. Rasmus Lerdorf (creator of PHP) starts off by labelling the request as bogus and goes through a long chain of bad reasoning to try to justify the warning. Then, finally, this exchange takes place:
Giorgio
i know, but:
abstract class cA
{
//static function A(){self::B();} error, undefined method
static function A(){static::B();} // good
abstract static function B();
}
class cB extends cA
{
static function B(){echo "ok";}
}
cB::A();
Rasmus
Right, that is exactly how it should work.
Giorgio
but it is not allowed :(
Rasmus
What's not allowed?
abstract class cA {
static function A(){static::B();}
abstract static function B();
}
class cB extends cA {
static function B(){echo "ok";}
}
cB::A();
This works fine. You obviously can't call self::B(), but static::B()
is fine.
The claim by Rasmus that the code in his example "works fine" is false; as you know, it throws a strict mode warning. I guess he was testing without strict mode turned on. Regardless, a confused Rasmus left the request erroneously closed as "bogus".
And that's why the warning is still in the language. This may not be an entirely satisfying explanation - you probably came here hoping there was a rational justification of the warning. Unfortunately, in the real world, sometimes choices are born from mundane mistakes and bad reasoning rather than from rational decision-making. This is simply one of those times.
Luckily, the estimable Nikita Popov has removed the warning from the language in PHP 7 as part of PHP RFC: Reclassify E_STRICT notices. Ultimately, sanity has prevailed, and once PHP 7 is released we can all happily use abstract static without receiving this silly warning.
static methods belong to the class that declared them. When extending the class, you may create a static method of the same name, but you are not in fact implementing a static abstract method.
Same goes for extending any class with static methods. If you extend that class and create a static method of the same signature, you are not actually overriding the superclass's static method
EDIT (Sept. 16th, 2009)
Update on this. Running PHP 5.3, I see abstract static is back, for good or ill. (see http://php.net/lsb for more info)
CORRECTION (by philfreo)
abstract static is still not allowed in PHP 5.3, LSB is related but different.
There is a very simple work around for this issue, which actually makes sense from a design point of view. As Jonathan wrote:
Same goes for extending any class with static methods. If you extend that class and create a static method of the same signature, you are not actually overriding the superclass's static method
So, as a work around you could do this:
<?php
abstract class MyFoo implements iMyFoo {
public static final function factory($type, $someData) {
// don't forget checking and do whatever else you would
// like to do inside a factory method
$class = get_called_class()."_".$type;
$inst = $class::getInstance($someData);
return $inst;
}
}
interface iMyFoo {
static function factory($type, $someData);
static function getInstance();
function getSomeData();
}
?>
And now you enforce that any class subclassing MyFoo implements a getInstance static method, and a public getSomeData method. And if you don't subclass MyFoo, you can still implement iMyFoo to create a class with similar functionality.
I know this is old but....
Why not just throw an exception the that parent class's static method, that way if you don't override it the exception is caused.
I would argue that an abstract class/interface could be seen as a contract between programmers. It deals more with how things should look/ behave like and not implement actual functionality. As seen in php5.0 and 5.1.x it's not a natural law that prevents the php developers from doing it, but the urge to go along with other OO design patterns in other languages. Basically these ideas try to prevent unexpected behavior, if one is already familiar with other languages.
I don't see any reason to forbid static abstract functions. The best argument that there is no reason to forbid them is, that they are allowed in Java.
The questions are:
- Are the technically feasable? - Yes, since the existed in PHP 5.2 and they exist in Java.
So whe CAN do it. SHOULD we do it?
- Do they make sense? Yes. It makes sense to implement an part of a class and leave another part of a class to the user. It makes sense in non-static functions, why shouldn't it make sense for static functions? One use of static functions are classes where there must not be more than one instance (singletons). For example an encryption engine. It does not need to exist in several instances and there are reasons to prevent this - for example, you have to protect only one part of the memory against intruders. So it makes perfect sense to implement one part of the engine and leave the encryption algorithm to the user.
This is only one example. If you are accustomed to use static functions you'll find lots more.
In php 5.4+ use trait:
trait StaticExample {
public static function instance () {
return new self;
}
}
and in your class put at the beggining:
use StaticExample;
Look into PHP's 'Late Static Binding' issues. If you're putting static methods on abstract classes, you're probably going to run into it sooner rather than later. It makes sense that the strict warnings are telling you to avoid using broken language features.
Related
Code beforehand fully valid code from 5.0.0 (without E_STRICT or E_DEPRECATED)
class A{
static public function b() {
}
public function c(){
$this->b();
}
}
$d = new A();
$d->c();
$d->b();
It's looks like inconsistent behaviour because you cannot use static properties from instance.
The PHP way is to steal and borrow from other languages whenever
possible ...
But I cannot find any programming language that supports similar behavior.
Why does PHP support it? What is the point of calling static methods as non-static?
Some explanation from support: Expected behavior
Actually, C++ and Java support this. It seems the PHP developers, after discussion, decided on implementation to match them.
After a bit of digging, I found this thread from February 2004, which is essentially their discussion about the implementation choices. Important tidbits from the discussion:
From Cristiano Duarte:
C++ allows $a->bar() when bar() is a static method (yes, it is called
in a static context there too).
IMO, there should be no error, warning or notice here.
I Agree. PHP is fine the way it is.
From Art:
Regardless of the final implementation, I think access to static methods and
static class variables should be consistent. Currently, you cannot access a
class variable via an object instance.
And for what it's worth, I see no reason why static methods cannot be called
from objects. Follow Java/C++ in this case.
Ultimately, a final decision From Wez:
Please drop this thread; we're not changing the behaviour of static.
It looks to me that it is just a syntax consideration here. Nothing here is inconsistent with the logic of static methods, it's still impossible to use $this in your static function, and therefore the function will not have access to instance properties or methods. It feels more like a shortcut than an inconsistency to me.
I have no use case of that, but I guess someone may find it useful with objects created with dynamic class names: you can still use the function even if you don't know it's class name.
I'm terribly sorry for asking such a silly question, but I'm new to OOP and trying to figure out what static methods are used for. Here's an example PHP code:
class foo{
static function bar(){
//do something here
}
public function baz(){
//do something different
}
}
Documentation says:
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class
However, the both methods from the example above can be accessed from outside of the class with like:
foo::bar();
foo::baz();
It works (at least for PHP 5.3 that I'm using) without instantiation of the class foo.
So, what's the point of using static methods, if the both ways work??
Forgive me once again for such a noob question. I've been really trying hard to find it out myself with no success. Thanks.
Static methods are globally available tools (helpers) and are often overused. Static methods are death to testability and should be avoided almost completely.
Their advantage as well as disadvantage is that they live in the global scope, you can call them from anywhere, which makes them code smells in most cases because they break encapsulation.
On language level, as Kolink mentions, things like mysqli:real_escape_string() make sense of course, but on application level, you usually don't want to pollute your global scope and break encapsulation like that. You'd rather think of what tools you really need and where and inject them bundled into meaningful groups (classes).
Your foo::baz() raises a warning in strict mode (which should always be on):
Strict standards: Non-static method foo:baz() should
not be called statically in yourfile.php on line x
Generally they can be used for "helper" functions, such as mysqli::real_escape_string(), where the function is relevant to the class but not locked to any specific instance of it.
In my company's codebase, i see functions used in both static and object context. For e.g. a class A has a function b() which is called both using A::b() and/or object_of_type_A->b(). I know this throws an error if strict is turned on. But I wanted to know if this is a bad practice and if yes, then why? Thanks for any answers.
Let me know if I don't make sense anywhere. I would be happy to clarify.
I'm not a php guy, but this sounds just like Java, where it's allowed but discouraged.
If it's static, I would strongly recommend only calling it in a static way. Otherwise it looks like it depends on the state of the object you're supposedly calling it on.
In Java the best example of this is Thread.sleep(). It's a static method which puts the current thread to sleep, always. But look at this code:
Thread t = new Thread(someTask);
t.start();
t.sleep(1000);
What does it look like that code is doing? It appears to be putting the other thread to sleep, whereas in fact it'll be the current thread that's sleeping. When you change it to a plain static call, it's more obvious:
Thread.sleep(1000);
That doesn't refer to t, so must be about the current thread.
Unless there's something specific to php where calling the static method via a variable gives you some sort of polymorphism, I suggest you stick to calling it in the static way. The fact that strict mode tells you to do this is a pretty strong hint, IMO :)
Here's some test code:
<?php
error_reporting(E_ALL | E_STRICT);
class Foo{
public function a(){
}
public static function b(){
}
}
$MyFoo = new Foo;
Foo::a(); // Strict Standards: Non-static method Foo::a() should not be called statically
Foo::b();
$MyFoo->a();
$MyFoo->b(); // No complaints
?>
PHP/5.3 warns about static calls to non-static methods, which is fine since they are subject to failure as soon as you want to access $this. But it does not complain about object context calls to static functions: there's nothing that can go wrong. This behaviour is documented:
Declaring class properties or methods
as static makes them accessible
without needing an instantiation of
the class. A property declared as
static can not be accessed with an
instantiated class object (though a
static method can)
[...]
Because static methods are callable
without an instance of the object
created, the pseudo-variable $this is
not available inside the method
declared as static.
So, as far as PHP is concerned, what you found in the code base is not wrong. However, I think it's slightly confusing.
There is 'currently' no harm in using it either way except of course when called as a static function you can't access the $this member.
The reason it errors in strict is because not writing your code to strict standards can result in errors occurring due to a lack of diligence. in the future it may also cause your code to break. a static function has no $this member and it may break parameter passing.
Play it safe only call static functions with A::b() type calls.
DC
Regarding accessing $this in a static function I found something a bit strange a while back (might be changed in later versions of PHP though, think I ran 5.2 or something).
You can read about it here but it's in swedish. But use google translate and it should be understandable.
http://www.phpportalen.net/viewtopic.php?p=560080#560080
I am using php 5.3, and yes, there is a bug open for that, but some think this is not a bug, and this makes me wonder.
abstract class A{
private function bobo(array $in){
//do something
}
}
class B extends A{
private function bobo($shmoo,$shmaa){
//do something
}
}
This throws an error. Shouldn't inheritance ignore private methods?!
'Declaration of B::bobo() should be
compatible with that of A::bobo()'
Note that the bug report is slightly off, as PHP will log this message any time you have an error level of E_STRICT (or, more recently, regardless of your error level provided that you've set a custom error handler).
PHP's visibility rules clearly demonstrate that a child lacks the ability to see its parent's private members, which I doubt is all that surprising to anyone. If the child can't see its parent's methods, I don't understand how it can have a duty to obey their definitions.
I personally think that the bug being marked as bogus without any explanation of why it wasn't a real flaw (since it's non-obvious and I couldn't find any mention of it in the documentation) is a bit wrong, but yeah. That aside, I'm of the opinion line 2669 in zend_compile.c should actually read as follows:
} else if (child->prototype &&
(EG(error_reporting) & E_STRICT || EG(user_error_handler))) {
...which would avoid the error popping up when the parent's method was marked private. Given that you always have the option not logging E_STRICT though, and it doesn't really negatively impact anything, I suppose it's not really a big deal. I definitely don't see how it could have been intentional, but I'm not a PHP engine developer either.
I think there are two possibilities here. Either it's a bug or the documentation on PHP.net/manual is incorrect. Here are three sections of the PHP manual. First on inheritance:
Object Inheritance
Inheritance is a well-established
programming principle, and PHP makes
use of this principle in its object
model. This principle will affect the
way many classes and objects relate to
one another.
For example, when you extend a class,
the subclass inherits all of the
public and protected methods from the
parent class. Unless a class overrides
those methods, they will retain their
original functionality.
This is useful for defining and
abstracting functionality, and permits
the implementation of additional
functionality in similar objects
without the need to reimplement all of
the shared functionality.
And on abstract classes:
Class Abstraction
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance
of a class that has been defined as abstract. Any class that contains at least one
abstract method must also be abstract. Methods defined as abstract simply declare the
method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's
class declaration must be defined by the child; additionally, these methods must be
defined with the same (or a less restricted) visibility. For example, if the abstract
method is defined as protected, the function implementation must be defined as either
protected or public, but not private.
Finally, interfaces
Object Interfaces
Object interfaces allow you to create code which specifies which methods a class must
implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class,
but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
Suffice it to say: there is nothing in the documentation that mentions inheritance of private methods. If there is a relationship between the parent and child method signatures, then it is not documented and the bug report should at least show someone that the documentation needs to be updated (if the decision to have this behavior is intentional). And if there was not supposed to be a relationship, then well, it's a real bug.
That's my opinion...
In the bug report when you remove the interface there isn't an error.
That makes it "more" strange behavior because the interface is just empty.
I guess this is a design decision of the language. The Java language developers decided that this should be possible.
Private methods should certainly not be ignored by inheritance, consider for example Template method pattern where you may override behavior of a function in a derived class, but the parent class can still call that function
public class Parent {
public final function doThings() {
$this->initialize();
$this->customStuff();
$this->cleanup();
}
private final function initialize() {
// initialize processing
}
private final function cleanup() {
// cleanup processing
}
private function customStuff() {
// parent specific processing
}
}
public class Derived extends Parent {
private function customStuff() {
parent::customStuff();
// + derived class specific processing
}
}
Calling doThings method on Derived class instance will do parent specific processing, but because of possibility to override private methods it is still possible to take advantage of the extension point provided by the non-final parent class customStuff method.
EDIT: Also PHP method signature consists of only the method name as you can define a method taking zero parameters and still call it with multiple parameters. Function can then access the arguments using func_get_args function.
Are there any reasons I should not create a final class with static methods to avoid that some internal functions are called?
final class ModuleGlobalFunctions {
static public function generateWord {
$result = '';
while (strlen($result) < 12) {
$result = self::generateSyllable();
}
return $result
}
static private function generateSyllable() {
// Generates a random syllable.
// …
}
}
$word = ModuleGlobalFunctions::generateWord();
// It raises an error.
$syllable = ModuleGlobalFunctions::generateSyllable();
Creating a class to shield off private functions is a good idea. This way, a public method in the class can call a private method, without making the private method callable from outside the class.
Making a class final is also a good idea, as this indicates that the class has not been designed with overloading in mind, and makes the class simpler.
Making the class static is a bad idea, because it tightly couples the caller to the class. If you call Test::generateWord(), this will always use the Test class. However, if you use $test->generateWord(), you can pass in another class, which creates other words. This makes it easier to change the software and easier to unit test it.
Well, personally, I would recommend using classes to group similar logic. So in your case (the example you provided), it's a good idea.
As for final, it's a toss up. I prefer to use abstract to prevent instantiation (since PHP doesn't support static classes). If you do use final, I would suggest adding a private constructor to prevent instantiation: private function __construct() {}...
Personally, I like the concept of keeping it static. The reason is three fold. First, it's easier on memory (since there are no instances to keep track of). Second, it's faster (A static method call is faster than an instance method call). Third, and more importantly, it makes sense. Instances have a state (that's why they are instances). Does your class need a state? If so, then use an instance. If not, that's exactly what static classes are meant for...
As for passing an instance as Sjoerd mentions, you can do that with static classes (and actually be less tightly coupled than with instances). Here's the reason. Unless you require (and check for) an interface or inheritance, you have no idea if the object actually implements the method generateWord(). But, if you pass in a callback, it doesn't matter how the method is accessed (or its underlying construction), all that matters is that it has the same (or similar) syntax (with respect to parameters and return values). Now, interfaces are a better solution to this (since it enforces the interface), but they require pretty deep understanding of OOP to get the design right. In a pinch, a callback will work quite fine for that case...