有人可以告诉我为什么这可能吗?私有属性只能从类本身进行更改。 s :: $ c是可读的(getC()),但为什么我可以写它?
<?php
class s{
private $c;
public function __construct() {
$this->c = new t;
}
public function getC() {
return $this->c;
}
}
class t {
public $a = 1;
public $b = 2;
}
$x = new s();
$x->getC()->a = 5;
echo $x->getC()->a;
?>
输出:5
答案 0 :(得分:5)
您通过公开$c
方法公开了getC()
。现在,任何人/任何人都可以通过使用$c
功能访问getC()
,任何人都可以随时访问$a
,因为它首先是公开的。
如果您希望类$a
的值$b
和t
为只读,那么您可以将他们设为私有,每个都有一个访问者像getA()
和getB()
这样的方法。例如:
class s {
private $c;
public function __construct() {
$this->c = new t;
}
public function getC() {
return $this->c;
}
}
class t {
private $a = 1;
private $b = 2;
public function getA() {
return $this->a;
}
public function getB() {
return $this->b;
}
}
答案 1 :(得分:3)
当php返回一个没有复制它的对象时,它会返回一个指针(引用)到内存中的对象。 因此,您所做的每一项更改都会影响原始对象。
为了防止它,您可以在返回之前克隆该对象
public function getC() {
return clone $this->c;
}
答案 2 :(得分:1)
这是预期的行为。
“私人”表示您无法直接使用$x->c
。
$x->getC()
是s的函数,因此可以访问s的私有成员。 getC
是公开的,因此您可以在任何地方调用该方法。
简而言之,因为你暴露了getC
(C的“getter”),你可以在任何地方读取C的值。您无法做的是$x->getC() = 2;
。