前言
当我们试图获取一个不可达属性时(比如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;
}
}
会产生一个报错
当加入了__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)