According to the PHP manual, a class like this:
abstract class Example {}
cannot be instantiated. If I need a class without instance, e.g. for a registry pattern:
class Registry {}
// and later:
echo Registry::$someValue;
would it be considered good style to simply declare the class as abstract? If not, what are the advantages of hiding the constructor as protected method compared to an abstract class?
Rationale for asking: As far as I see it, it could a bit of feature abuse, since the manual refers to abstract classes more as like blueprints for later classes with instantiation possibility.
Update: First of all, thanks for all the answers! But many answers sound quite alike: 'You cannot instantiate an abstract class, but for a registry, why not using a singleton pattern?'
Unfortunately, that was more or less exactly a repeat of my question. What is the advantage of using a singleton pattern (a.k.a. hiding __construct()
) compared to just declaring it abstract
and not having to worry about that? (Like, e.g., it is a strong connotation between developers, that abstract
classes are not actually used or so.)
Declaring abstract method static If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.
The Y() that function X() is trying to call is the parent class Y(), which is itself an abstract function. So, using abstract and static on the same method defeats each other purpose. This is the reason why PHP 5.2+ does not allow abstract static class methods.
static keyword in class definition means that all methods in the class are static as well. But static methods cannot be inherited or overridden, and that is why they can't be abstract.
$this is not available in static methods. To simplify the reasoning, think of static methods as glorified global functions.
If your class is not meant to define some super-type, it should not be declared as abstract
, I'd say.
In your case, I would rather go with a class :
__construct
and __clone
as private methods
Now, why use a Singleton, and not only static methods ? I suppose that, at least a couple of reasons can be valid :
__construct
and __clone
private, and add some getInstance
method.$this
, properties, ...__callStatic
has only been introduced in PHP 5.3__getStatic
, __setStatic
, ...
This being said, yes, some code like this :
abstract class MyClass {
protected static $data;
public static function setA($a) {
self::$data['a'] = $a;
}
public static function getA() {
return self::$data['a'];
}
}
MyClass::setA(20);
var_dump(MyClass::getA());
Will work... But it doesn't feel quite natural... and this is a very simple example (see what I said earlier with Late Static Binding, and magic methods).
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