因为您正在使用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::$reference
只有一个实例,将被共享给所有的extended_class
实例。如果这不是你想要的结果,那么这不会起作用。
看起来您真正担心的是内存或资源使用情况。在PHP中,所有对象都是传递引用的。这意味着将对象作为参数传递、创建副本等操作不会消耗额外的内存。如果您需要在许多其他对象中引用一个对象,这样做不会消耗额外的内存。
如果我有一个extended_class
和另一个完全相同的类(比如extended_class1
),它们也会共享引用吗?还是所有extended_class
实例都共享一个引用,而所有extended_class1
实例将共享另一个引用(理想情况)?
看起来共享是基于静态变量定义的位置。以下是两个例子,都来自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。
static
行为发生了一些重大变化,如果你被困在旧版本上,那么你得到的答案将会非常不同。 - Charles