PHP魔术方法__get && __set

万能青年
2022-03-15 / 0 评论 / 146 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年07月10日,已超过851天没有更新,若内容或图片失效,请留言反馈。

前言

当非法调用私有变量时

<?php


namespace App\Http\Controllers;


class TestController
{
    public $name = '你的名字';
    private $age = 18;

}
<?php


namespace App\Http\Controllers;


class IndexController
{
    private $class;
    public function __construct(TestController $test)
    {
        $this->class = $test;
    }

    public function test()
    {
        return $this->class->age;
    }
}

会产生一个报错

当加入了__get() 方法

<?php


namespace App\Http\Controllers;


class TestController
{
    public $name = '你的名字';
    private $age = 18;
    private $sex = '男';

    function __get($name){
        echo '姓名: '.$name.' 年龄:'.$this->age.'-性别'.$this->sex;
    }
}

调用

<?php


namespace App\Http\Controllers;


class IndexController
{
    private $class;
    public function __construct(TestController $test)
    {
        $this->class = $test;
    }

    public function test()
    {
        return $this->class->age;
    }
}

结果

姓名: age 年龄:18-性别男

__set() 同理

<?php


namespace App\Http\Controllers;


class TestController
{
    public $name = '你的名字';
    private $age = 18;
    private $sex = '男';

    function __set($age,$val){
        $this->$age = $val;
    }

    public function getAge()
    {
        return $this->age;
    }
}

调用

<?php


namespace App\Http\Controllers;


class IndexController
{
    private $class;
    public function __construct(TestController $test)
    {
        $this->class = $test;
    }

    public function test()
    {
         $this->class->age = 30;
         return $this->class->getAge();
    }
}

结果

30
0

评论 (0)

取消