Reputation: 4877
1) Is it possible to store a reference to an abstract class in a variable like so:
abstract class A implements X {}
$A = A; //This doesn't work
2) Ultimately I want to be able to pass a reference to an abstract class to a method or function.
class Y { public function __construct(X $X){} }
$Y = new Y($A);
It would even be satisfactory to be able to do something like this:
abstract class A { public static $staticProperty; }
class Y {
public function __construct($X){
echo $X::$staticProperty; //Doesn't work
}
}
$Y = new Y('A');
Upvotes: 0
Views: 1286
Reputation: 106385
As you cannot instantiate an abstract class, you're restricted to working with static properties (and constants) only. And since PHP 5.3, you can use variables to specify the queried class, with only restriction:
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
So you can pass a classname instead; it will work as an anchor for an abstract class. For example (demo):
abstract class Foo { static $bar = 5; }
abstract class Bah { static $bar = 6; }
function echoBar($classname) {
echo $classname::$bar;
}
echoBar('Foo'); // 5
echoBar('Bah'); // 6
Upvotes: 1