php 5.3 後新增了 __call 與__callStatic 魔法方法。
__call 當要呼叫的方法不存在或權限不足時,會自動呼叫__call 方法。
__callStatic 當呼叫的靜態方法不存在或權限不足時,會自動呼叫__callStatic方法。
__call($funcname, $arguments)
__callStatic($funcname, $arguments)
參數說明:
#$funcname String 呼叫的方法名稱。
$arguments Array 呼叫方法時所帶的參數。
__call 範例
<?php class Member{ protected $memberdata = array(); public function __call($func, $arguments){ list($type, $name) = explode('_', $func); if(!in_array($type, array('set','get')) || $name==''){ return ''; } switch($type){ case 'set': $this->memberdata[$name] = $arguments[0]; break; case 'get': return isset($this->memberdata[$name])? $this->memberdata[$name] : ''; break; default: } } } class User extends Member{ public function show(){ if($this->memberdata){ foreach($this->memberdata as $key=>$member){ echo $key.':'.$member.'<br>'; } } } } class Profession extends Member{ public function show(){ if($this->memberdata){ foreach($this->memberdata as $key=>$member){ echo $key.':'.$member.'<br>'; } } } } $userobj = new User(); $userobj->set_name('fdipzone'); $userobj->set_age(29); $userobj->show(); $probj = new Profession(); $probj->set_profession('IT SERVICE'); $probj->set_price(2500); $probj->show(); ?>
__callStatic範例
<?php class Member{ protected static $memberdata = array(); public static function __callStatic($func, $arguments){ list($type, $name) = explode('_', $func); if(!in_array($type, array('set','get')) || $name==''){ return ''; } $feature = get_called_class(); switch($type){ case 'set': self::$memberdata[$feature][$name] = $arguments[0]; break; case 'get': return isset(self::$memberdata[$feature][$name])? self::$memberdata[$feature][$name] : ''; break; default: } } } class User extends Member{ public static function show(){ $feature = get_called_class(); if(self::$memberdata[$feature]){ foreach(self::$memberdata[$feature] as $key=>$member){ echo $key.':'.$member.'<br>'; } } } } class Profession extends Member{ public static function show(){ $feature = get_called_class(); if(self::$memberdata[$feature]){ foreach(self::$memberdata[$feature] as $key=>$member){ echo $key.':'.$member.'<br>'; } } } } User::set_name('fdipzone'); User::set_age(29); User::show(); Profession::set_profession('IT SERVICE'); Profession::set_price(2500); Profession::show(); ?>
本文說明了php __call 與__callStatic 的內容,更多相關知識請關注php中文網。
相關推薦:
關於PHPMailer - PHP email transport class 的相關解說
#以上是關於php __call 與 __callStatic 的內容講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!