前言
当我们试图获取一个不可达属性时(比如private),类会自动调用__get函数。
当试图设置一个不可达属性时(比如private),类会自动调用__set函数
当非法调用私有变量时
代码语言:javascript复制<?php
namespace AppHttpControllers;
class TestController
{
public $name = '你的名字';
private $age = 18;
}
代码语言:javascript复制<?php
namespace AppHttpControllers;
class IndexController
{
private $class;
public function __construct(TestController $test)
{
$this->class = $test;
}
public function test()
{
return $this->class->age;
}
}
会产生一个报错
Cannot access private property AppHttpControllersTestController::$age
当加入了__get() 方法
代码语言:javascript复制<?php
namespace AppHttpControllers;
class TestController
{
public $name = '你的名字';
private $age = 18;
private $sex = '男';
function __get($name){
echo '姓名: '.$name.' 年龄:'.$this->age.'-性别'.$this->sex;
}
}
调用
代码语言:javascript复制<?php
namespace AppHttpControllers;
class IndexController
{
private $class;
public function __construct(TestController $test)
{
$this->class = $test;
}
public function test()
{
return $this->class->age;
}
}
结果
姓名: age 年龄:18-性别男
可以看出test方法自动调用了 __get(),并可以访问私有变量。
__set() 同理
代码语言:javascript复制<?php
namespace AppHttpControllers;
class TestController
{
public $name = '你的名字';
private $age = 18;
private $sex = '男';
function __set($age,$val){
$this->$age = $val;
}
public function getAge()
{
return $this->age;
}
}
调用
代码语言:javascript复制<?php
namespace AppHttpControllers;
class IndexController
{
private $class;
public function __construct(TestController $test)
{
$this->class = $test;
}
public function test()
{
$this->class->age = 30;
return $this->class->getAge();
}
}
结果
30