当我们试图获取一个不可达属性时(比如private),类会自动调用__get函数。
当试图设置一个不可达属性时(比如private),类会自动调用__set函数
<?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;
}
}
会产生一个报错
Cannot access private property App\Http\Controllers\TestController::$age
<?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-性别男
可以看出test方法自动调用了 __get(),并可以访问私有变量。
<?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