gpt4 book ai didi

PHP 变量覆盖

转载 作者:IT王子 更新时间:2023-10-28 23:52:44 25 4
gpt4 key购买 nike

当我尝试以与覆盖 PHP 中的类方法相同的方式覆盖类变量时。喜欢:

class DataMapper {
protected $_name = null;

public function printName() {
echo $this->_name;
}
}

class Model extends DataMapper {
protected $_name = 'Ana';
}

$test = new Model();
$test->printName();

打印的是“安娜”。

为什么 PHP 可以做这样的事情?它打破了面向对象范式的规律

最佳答案

不是。这就是 PHP 应该如何工作的。看看PHP Classes and Objects Visibility .

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

因为模型扩展了 DataMapper,它可以访问它的函数、变量等,但它可以覆盖它们,这就是发生的事情。尽管您的函数位于 DataMapper 类中,但它是从名称设置为 Ana 的 Model 类调用(并由其继承)。

关于PHP 变量覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6339150/

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