gpt4 book ai didi

php - 为什么PHP中静态成员变量在多次实例化对象时会继承该值?

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

我正在测试静态关键字,看看它到底是如何工作的,我遇到了这个,我不明白发生了什么。

考虑两个类 ClassNameAClassNameB 并使用以下代码。

没有静态关键字的ClassNameA

class ClassNameA
{
private $name;

public function __construct($value) {
if($value != '') {
$this->name = $value;
}
$this->getValue();
}
public function getValue() {
echo $this->name;
}
}

带有静态关键字的ClassNameB

class ClassNameB
{
private static $name;

public function __construct($value) {
if($value != '') {
self::$name = $value;
}
$this->getValue();
}
public function getValue() {
echo self::$name;
}
}

当我使用 ClassNameA 多次实例化对象时

$a = new ClassNameA(12);
echo '<br/>';
$a = new ClassNameA(23);
echo '<br/>';
$a = new ClassNameA(''); //Argument given is Empty here

它输出以下内容

12
23

现在当我使用 ClassNameB 多次实例化对象时

$a = new ClassNameB(12);
echo '<br/>';
$a = new ClassNameB(23);
echo '<br/>';
$a = new ClassNameB(''); //Argument given is Empty here

它输出以下内容

12
23
23

请注意,即使传递的参数为空,它也会获取额外的值 23。这是一个错误吗?或者我错过了什么?

最佳答案

这是静态属性的本质。静态属性是类的一种属性,而不是对象的属性。

当您传递空白时,根据条件,静态属性的值将不会更新,并且最后一个值仍然存在于静态属性中。

由于静态属性不与任何对象绑定(bind),因此无需任何对象即可使用它。

$a = new ClassNameB(12); //static property is set to 12
echo '<br/>';
$a = new ClassNameB(23); //static property is update to 23
echo '<br/>';
$a = new ClassNameB(''); //static property is not updated here it is still 23

编辑

你可以这样理解:-

if($value != '') {
$this->name = $value; //
}

上面的代码所做的是设置当前对象(正在初始化的对象)的属性值。

所以当你写的时候

$a = new ClassNameA(12);

它所做的是将对象 aname 属性设置为 12

$a = new ClassNameA(23);

它所做的是将对象 aname 属性设置为 23

但是当属性是静态时,则适用于整个类而不是任何对象。

所以当你写

if($value != '') {
self::$name = $value;
}

上面的代码设置静态属性值。请注意,这里您编写了 self 而不是 $this,这使得它仅用于此类,而不用于任何对象。

我试图更好地解释它,但不知道它如何向您解释。

关于php - 为什么PHP中静态成员变量在多次实例化对象时会继承该值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6314452/

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