php visibility modifier令人困惑的部分

时间:2017-10-16 08:53:14

标签: php oop

我是PHP OOP的初学者,并尝试学习PHP可见性修饰符 在private修饰符中,我可以从它自己的类访问私有属性和方法 但是您可以看到我的代码,我可以从名为 VisibilityModifierChild 的子类访问私有属性。请查看我的代码注释以获得更好的理解,或者您可以在在线PHP解释器中运行代码以获取更多信息。

class VisibilityModifier {
    public $pub_variable = "public property";
    protected $pro_variable = "protected property - <strong>getPro() method</strong>";
    private $pri_variable = "private property - <strong>getPri() method</strong>";

    //set getter for protected variable
    public function getPro() {
        return $this->pro_variable;
    }
    //set getter for private variable
    public function getPri() {
        return $this->pri_variable;
    }
}

class VisibilityModifierChild extends VisibilityModifier {
    public function setPubVariable($set) {
        $this->pub_variable = $set;
    }

    public function setProVariable($set) {
        $this->pro_variable = $set;
    }

    // cannot set the value but it does't give any warning and error -- sound cofusing
    public function setPriVariable($set) {
        $this->pri_variable = $set;
    }

    // set and get a private property from child class -- sound confusing
    public function getPrivateByChild ($set) {
        $this->pri_variable = $set;
        return $set;
    }

}


$visible = new VisibilityModifier();
$visible_child = new VisibilityModifierChild();


echo $visible->pub_variable . "<strong style=\"color:green\">-Looks Good</strong><br>";
$visible_child->setPubVariable("child access public property");
echo $visible_child->pub_variable . "<strong style=\"color:green\"> -Looks Good</strong><br>";

echo '<hr>';

// echo $visible->pro_variable . "<br>"; 
echo $visible_child->getPro() . "<strong style=\"color:green\"> -Looks Good</strong><br>";
$visible_child->setProVariable("child access protected property<strong style=\"color:green\"> -Looks Good</strong>");
echo $visible_child->getPro() . "<br>";

echo '<hr>';


// echo $visible->pri_variable . "<br>"; 
echo $visible->getPri() . "<strong style=\"color:green\"> -Looks Good</strong><br>";
$visible_child->setPriVariable("child access private property") . "<br>";
echo $visible_child->getPri() . "<strong style=\"color:red\"> -sound confusing</strong><br>";
echo $visible_child->getPrivateByChild("child can access private property<strong style=\"color:red\"> -sound confusing</strong>") . "<br>";

1 个答案:

答案 0 :(得分:3)

当您转储子实例时,您会看到现在有两个属性&#34; pri_variable&#34;:

object(VisibilityModifierChild)#2 (4) {
  ["pub_variable"]=>
  string(15) "public property"
  ["pro_variable":protected]=>
  string(53) "protected property - <strong>getPro() method</strong>"
  ["pri_variable":"VisibilityModifier":private]=>
  string(51) "private property - <strong>getPri() method</strong>"
  ["pri_variable"]=>
  string(29) "child access private property"
}

您无权访问的未更改的私有属性以及您在调用setter时动态设置的私有属性。

由于子类无法看到私有属性,因此它只会在其自己的实例范围(this)中创建一个具有相同名称的新属性。它可能看起来好像您正在访问私有财产,但您实际上是在创建一个新属性。私有财产没有变化。