因为您使用PHP 5.3,您可以使用
late static binding在运行时解决对正确类的静态调用.
class base_class {
public function doSomethingWithReference(){
static::$reference->doSomething();
}
}
class extended_class extends base_class{
protected static $reference;
public function __construct($ref){
static::$reference = $ref;
}
}
大胖提醒:一个extended_class :: $引用将在所有的extended_class实例之间共享.如果这不是你打算的话,这是不行的.
你似乎真的担心内存或资源的使用.在PHP中,所有对象都通过引用传递.这意味着传递一个对象作为一个参数,或创建一个它的副本等,不会消耗额外的内存.如果您需要引用一些其他对象的对象,这样做不会消耗额外的内存.
If I had extended_class and another identical class (say extended_class1) would they share the reference as well? or would all extended_class’ instances share one reference, while all extended_class1′ instances would share another (the ideal case)?
看起来共享是基于定义静态变量的位置.两个例子,都是从PHP交互提示:
php > class Shared { public $me; public function __construct($me) { $this->me = $me; } }
php > class Base { protected static $ref; public function foo() { echo static::$ref->me, "\n"; } }
php > class Inherit_1 extends Base { public function __construct($ref) { static::$ref = $ref; } }
php > class Inherit_2 extends Base { public function __construct($ref) { static::$ref = $ref; } }
php > class Inherit_3 extends Inherit_1 {}
php > $shared_1 = new Shared(1)
php > ;
php > $shared_2 = new Shared(2);
php > $shared_3 = new Shared(3);
php >
php > $in_1 = new Inherit_1($shared_1);
php > $in_2 = new Inherit_2($shared_2);
php > $in_3 = new Inherit_3($shared_3);
php >
php > $in_1->foo();
3
php > $in_2->foo();
3
php > $in_3->foo();
3
在这种情况下,由于引用存在于基类中,所以每个人都看到相同的引用.我想这有点有道理.
当我们声明每个子类的引用时,大部分时间会发生什么?
php > class Shared { public $me; public function __construct($me) { $this->me = $me; } }
php > class Base { public function foo() { echo static::$ref->me, "\n"; } }
php > class Inherit_1 extends Base { protected static $ref; public function __construct($ref) { static::$ref = $ref; } }
php > class Inherit_2 extends Base { protected static $ref; public function __construct($ref) { static::$ref = $ref; } }
php > class Inherit_3 extends Inherit_1 {}
php > class Inherit_4 extends Inherit_1 { protected static $ref; }
php > $shared_1 = new Shared(1);
php > $shared_2 = new Shared(2);
php > $shared_3 = new Shared(3);
php > $shared_4 = new Shared(4);
php > $in_1 = new Inherit_1($shared_1);
php > $in_2 = new Inherit_2($shared_2);
php > $in_3 = new Inherit_3($shared_3);
php > $in_4 = new Inherit_4($shared_4);
php > $in_1->foo();
3
php > $in_2->foo();
2
php > $in_3->foo();
3
php > $in_4->foo();
4
因为3从1继承而没有声明它是自己的静态属性,它继承了1.当我们将3设置为Shared(3)时,它覆盖了1个现有的Shared(1).
结论:为了使这个工作,需要在需要单一唯一引用的每个类中声明该属性.请注意,此代码从5.4.x开始有效.