① __get/__set:將對象的屬性進行接管
當訪問一個不存在的對象屬性時:
index.php
$obj = new /Common/Object();
//在php中訪問一個不存在的對象屬性時
echo $obj->title;
會拋出一個錯誤:Notice: Undefined property: Common/Object::$title in D:/practise/php/design/psr0/index.php on line 9
當在Common/Object.php 中添加 __set 和 __get 方法后
Object.php
class Object{
function __set($key,$value){
}
function __get($key){
}
}
再執行 index.php,不會再報錯。
再次修改 Common/Object.php
class Object{
protected $array = array();
function __set($key,$value){
var_dump(__METHOD__);
$this->array[$key] = $value;
}
function __get($key){
var_dump(__METHOD__);
return $this->array[$key];
}
}
$obj = new /Common/Object();
$obj->title = 'hello';
echo $obj->title;
執行 index.php,頁面輸出:
② __call/__callStatic:控制 PHP 對象方法的調用(__callStatic 用來控制類的靜態方法)
當執行一個不存在的php方法時
index.php:
$obj = new /Common/Object();
//當執行一個不存在的php方法時
$obj->test('hello',123);
執行 index.php 會報一個致命錯誤:Fatal error: Call to undefined method Common/Object::test() in D:/practise/php/design/psr0/index.php on line 9
如果在 Common/Object 中定義一個__call 方法,則會在方法不存在時自動回調:
class Object{
function __call($func, $param){ //$func 方法名 $param 參數
var_dump($func, $param);
return "magic function/n"; //返回一個字符串作為返回值
}
}
index.php
$obj = new /Common/Object();
//當執行一個不存在的php方法時
echo $obj->test('hello',123);
頁面輸出:
當調用一個不存在的靜態方法時
Common/Object.php
class Object{
static function __callStatic($name, $arguments) {
var_dump($name, $arguments);
return "magic function/n"; //返回一個字符串作為返回值
}
}
注意:__callStatic 方法也要聲明成靜態方法
index.php
//執行一個不存在的靜態方法
echo Common/Object::test("hello",1234);
執行 index.php ,頁面輸出:
③ __toString:將一個 PHP 對象轉換成一個字符串
index.php
$obj = new /Common/Object();
echo $obj;
此時會報錯: Catchable fatal error: Object of class Common/Object could not be converted to string in D:/practise/php/design/psr0/index.php on line 8
在 Object.php 中添加 __toString 方法
class Object{
function __toString() {
return __CLASS__;
}
}
④ __invoke:將一個 PHP 對象當成一個函數來執行時,會回調此魔術方法
index.php
$obj = new /Common/Object();
echo $obj("test");
class Object{
function __invoke($param) {
var_dump($param);
return 'invoke';
}
}
頁面輸出:
新聞熱點
疑難解答