PHP PHP 私有字段 private 也可以外部访问

jameson · 2019-11-26 15:03:35 · 热度: 29

由 private 定义的类成员则只能被其所在类访问。但是下面我们写一个小程序,可以在类的外部访问该 private 字段。

<?php
class codercto {
    private $domain;
    function __get($key){
        return "使用get访问属性".$this->$key;
    }
    function __set($key,$value){
        $this->$key = $value;
        echo("使用set设置属性$key, 赋值为:<font color=red>$value</font>");
    }
}

$ins = new codercto();
$ins->domain = "codercto.com";
echo '<br />';
echo $ins->domain;
?>

程序运行结果:

使用set设置属性domain, 赋值为:codercto.com
使用get访问属性codercto.com

php类中如有字段domain是私有字段,实例化后也可以直接访问该字段,不知道为什么要这样做?有什么优点?既然是私有字段,就不应该能够直接访问,应该只能通过类中的方法来访问(不是通过__get__set)。

既然是私有的了就不该能够直接访问,我觉得这样比较合理些。

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册