为什么__set()和__get()私有了,还是可以执行?

来源:互联网 发布:淘宝直通车的使用规则 编辑:程序博客网 时间:2024/05/01 23:21

    //__set()和__get()方法私有了,还是可以执行,
    //是因为目前程序的指针已经在类内了。而类内可以执行封装的方法
    //类内执行私有方法,不会出现任何错误。

    //__set()和__get()其实就是php内置的方法

class Computer {


        private $_name;
        private $_model;
        private $_cpu;
        

        //用private私有__set()和__get()方法,防止外部直接访问


        private function __set($_key,$_value) {
            $this->$_key = $_value;
        }
        private function __get($_key) {
            return $this->$_key;
        }
    }

    $computer = new Computer();
    $computer->_name = '联想';
    $computer->_cpu = '四核';
    $computer->_model = 'i7';

    echo $computer->_name;
    echo $computer->_cpu;

    echo $computer->_model;



0 0
原创粉丝点击