gpt4 book ai didi

php - 通过引用分配静态属性在 PHP5 和 PHP7 之间表现不同

转载 作者:行者123 更新时间:2023-12-04 00:56:37 24 4
gpt4 key购买 nike

从 PHP 5 升级到 PHP 7 后,以下代码产生不同的结果:

abstract class TheParent {
public static $prop;

public function __construct( $val ) {
static::set_prop($val);
}

public static function set_prop( $val ) {
$ref_reset = $val;
static::$prop =& $ref_reset;
}
}

class Child extends TheParent {
// public static $prop; //<-- not declared on purpose
}

class Child2 extends TheParent {
// public static $prop; //<-- not declared on purpose
}

$c = new Child('do');
$c2 = new Child2('re');

echo 'Child: ' . Child::$prop . '<br>';
echo 'Child2: ' . Child2::$prop . '<br>';
echo 'TheParent: ' . TheParent::$prop;

在 PHP5 中:

Child: do
Child2: re
TheParent:

在 PHP7 中:

Child: re
Child2: re
TheParent: re

我想要的输出是 PHP5 输出,因为我希望能够在所有扩展基(父)类的类中引用单个属性名称,但我不想重新声明该属性或设置它的方法在每个子类中(主要是为了避免将相同的属性/方法添加到数十个类的维护开销)。

PHP5 中的魔力似乎在于引用赋值(在对 SO 进行大量搜索之后,helpful answerers 提到通过引用设置“打破”了“引用集”,这允许每个子项中的属性类来保存单独的值)。我发现这是 PHP5 中一个非常优雅的解决方案。

在 PHP7 中有没有办法用相同或相似的代码达到相同的结果?

解决方法:

看起来这是 PHP 7.2 和 7.3 之间重大变化的结果,可能没有类似优雅的双行替代方案。重构我的代码后,我发现这个稍微更冗长的解决方法是有效的(并且满足了我的主要目标,即不必在子类中重新声明属性):

abstract class TheParent {
public static $props = [];

public function __construct( $val ) {
static::set_prop($val);
}

public static function set_prop( $val ) {
self::$props[static::class] = $val;
}

public static function get_prop() {
if( isset(self::$props[static::class]) )
return self::$props[static::class];
}
}

class Child extends TheParent {
// public static $prop; //<-- not declared on purpose
}

class Child2 extends TheParent {
// public static $prop; //<-- not declared on purpose
}

$c = new Child('do');
$c2 = new Child2('re');

echo 'Child: ' . Child::get_prop(). '<br>'; // 'do' in PHP 7.3
echo 'Child2: ' . Child2::get_prop() . '<br>'; // 're' in PHP 7.3
echo 'TheParent: ' . TheParent::get_prop(); // '' in PHP 7.3

最佳答案

这在 PHP 7.2 => 7.3 中改变了

Static Properties no longer separated by Reference Assignment

In PHP, static properties are shared between inheriting classes, unlessthe static property is explicitly overridden in a child class.However, due to an implementation artifact it was possible to separatethe static properties by assigning a reference. This loophole has beenfixed.

https://www.php.net/manual/en/migration73.incompatible.php

关于php - 通过引用分配静态属性在 PHP5 和 PHP7 之间表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62038730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com