PHP 变量覆盖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6339150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Variable Overriding
提问by brian
When I try to Override the class variable same way as override the class method in PHP. Like:
当我尝试以与覆盖 PHP 中的类方法相同的方式覆盖类变量时。喜欢:
class DataMapper {
protected $_name = null;
public function printName() {
echo $this->_name;
}
}
class Model extends DataMapper {
protected $_name = 'Ana';
}
$test = new Model();
$test->printName();
It's print 'Ana'.
它是印刷品“安娜”。
Why PHP can do such a thing like that ? It break the law of object oriented paradigm
为什么PHP可以做这样的事情?它打破了面向对象范式的规律
回答by Francois Deschenes
It's not. That's how PHP is supposed to work. Have a look at PHP Classes and Objects Visibility.
它不是。这就是 PHP 应该如何工作的。看看PHP 类和对象可见性。
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.
相同类型的对象可以访问彼此的私有成员和受保护成员,即使它们不是相同的实例。这是因为在这些对象内部时,实现特定的细节是已知的。
Because Model extends DataMapper, it has access to its functions, variables and such but it can override them which is what happened. Although your function lives in the DataMapper class, it's called from (and inherited by) the Model class in which the name is set to Ana.
因为 Model 扩展了 DataMapper,它可以访问它的函数、变量等,但它可以覆盖它们,这就是发生的事情。尽管您的函数位于 DataMapper 类中,但它是从名称设置为 Ana 的 Model 类调用(并由其继承)。
回答by BraedenP
I think you're just having trouble understanding what $this does. When you reference $this, it is actually referencing the current object.
我认为您只是无法理解 $this 的作用。当您引用 $this 时,它实际上是在引用当前对象。
When you inherit the DataMapper class, the printName() method is made accessible inside Model objects, but the $this reference still refers to the current Model object, $test.
当您继承 DataMapper 类时,printName() 方法可在 Model 对象内部访问,但 $this 引用仍指向当前 Model 对象 $test。
Since the $_name property of Model objects is instantiated to "Ana" it is printing Ana. This is exactly what is expected. Perhaps having another read through the theories of Inheritance and Scope would help you out with understanding what's going on here.
由于模型对象的 $_name 属性被实例化为“Ana”,它正在打印 Ana。这正是预期的结果。也许再读一遍继承和作用域的理论会帮助你理解这里发生了什么。
回答by Balanivash
I dont think this breaks the "law of OO". You have inherited the DataMapper class. And thus you have inherited the public function printName(). So when you call the function it acts like the function that belongs to the model class.
我不认为这违反了“OO 法则”。您已经继承了 DataMapper 类。因此您继承了公共函数printName()。因此,当您调用该函数时,它的作用就像属于模型类的函数。