PHP5成员可见度 [英] PHP5 member visibility
问题描述
有人可以向我解释一下,为什么可以在PHP中执行以下操作,但是,例如在C#或Java中却不能:
Could someone explain me, why is it possible to do the following in PHP, but, for example, not in C# or Java:
Class A {
protected $a = 'Howdy!';
}
Class B extends A {
public function howdy() {
$created = new A();
echo $created->a; <----- This is legal due to per-class visibility
}
}
$b = new B();
echo $b->howdy(); <----- Hence, no fatal error here
此行为似乎已指定 此处 ,但我不能了解造成这种情况的根本原因 (在我看来,不能简单地实现每类
可见性而不是每个实例
,而没有充分的理由)。
This behavior seems to be specified here, but I can't understand the fundamental reason behind this (to my mind, one can't simply implement the per-class
visibility instead of the per-instance
one without having a strong reason for that).
推荐答案
正如您所指定的那样,它不起作用的原因是PHP在类级别上实现了访问控制,而其他语言则使用实例级别的方法。
The reason it doesn't work is, as you specified, PHP implements access control on a class level, where other languages use an instance level approach.
为什么有用?它允许您的类在自身的其他实例上进行操作,而不会暴露其私有数据。让我们举一个简单的值对象示例:
Why is it useful? It allows your classes to operate on other instances of itself without exposing its private data. Let's take a simple value-object example:
class Int {
protected $value = 0;
public function __construct($value) {
$this->value = (int) $value;
}
public function add(Int $new) {
return new Int($new->value + $this->value);
}
}
$a = new Int(1);
$b = new Int(2);
$c = $a->add($b);
这使您可以保护受保护的信息,但仍可以在各个实例中使用它。
This lets you keep protected info encapsulated, yet still work with it across instances...
两种方法各有利弊...
There are pros and cons to both approaches...
这篇关于PHP5成员可见度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!