为什么你可以改变私有属性(对象)的值?

phi*_*opp 0 php oop getter private

有人可以告诉我为什么这是可能的吗?私有属性只能从类本身进行更改.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;
?>
Run Code Online (Sandbox Code Playgroud)

输出:5

Jon*_*uis 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;
    }
}
Run Code Online (Sandbox Code Playgroud)