58

外部调用类的私有属性

 5 years ago
source link: http://www.gubeiqing.cn/2018/09/23/php04/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PHP菜鸟

先来了解一下PHP类中的 __get__set 函数

当试图获取一个不可达属性时,类会自动调用 __get 函数。

当试图设置一个不可达属性时,类会自动调用 __set 函数。

首先,来看一下 __get 函数,先来获取一个可达属性试试:

<?php
    class A{
        public $a=1;
        private $b=2;
        function __get($name){
            echo 'you can get '.$name;
        }
    }
    $dy = new A();
    echo $dy->a;
?>

看一下它的返回:

没有问题,没有调用 __get 函数,现在我来访问一个私有的不可达属性:

<?php
    class A{
        public $a=1;
        private $b=2;
        function __get($name){
            echo 'you can get '.$name;
        }
    }
    $dy = new A();
    echo $dy->b;
?>

会发现:

you can get b

说明这里调用了 __get 函数,我再来看一下 __set 函数,同样也是先使用可达的 public 属性:

<?php
    class A{
        public $a;
        private $b;
        function __set($name,$val){
            echo 'you can get '.$name.$val;
        }
    }
    $dy = new A();
    $dy->a = 1;
    echo $dy->a;
?>

看一下输出:

使用成功,没有问题,接着我们来使用私有属性:

<?php
    class A{
        public $a;
        private $b;
        function __set($name,$val){
            echo 'you can get '.$name.$val;
        }
    }
    $dy = new A();
    $dy->b = 1;
    echo $dy->b;
?>

这时看到:

you can get b1

PHP Fatal error:  Cannot access private property A::$b in /usercode/file.php on line 11

这里调用了 __set 函数并提示我们不能使用类的私有属性。

现在来通过 __set 函数实现外部使用私有属性:

<?php
    class A{
        public $a;
        private $b;
        function __set($name,$val){
                $this->$name=$val;
        }
        function B(){
            echo $this->b;
        }
    }
    $dy = new A();
    $dy->b = 1;
    $dy->B();
?>

看一下输出:

说明使用成功。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK