重載
屬性重載與方法重載
PHP所提供的"重載"(overloading)是指動態地"建立"類屬性和方法。我們是通過魔術方法(magic methods)來實現的。
當調用當前環境下未定義或不可見的類屬性或方法時,重載方法會被調用。
所有的重載方法都必須被聲明為 public。
屬性重載
public void __set ( string $name , mixed $value )
public mixed __get ( string $name )
public bool __isset ( string $name )
public void __unset ( string $name )
在給不可訪問屬性賦值時,__set() 會被調用。
讀取不可訪問屬性的值時,__get() 會被調用。
當對不可訪問屬性調用 isset() 或 empty() 時,__isset() 會被調用。
當對不可訪問屬性調用 unset() 時,__unset() 會被調用。
參數 $name 是指要操作的變數名稱。__set() 方法的 $value 參數指定了 $name 變數的值。
屬性重載只能在對象中進行。在靜態方法中,這些魔術方法將不會被調用。所以這些方法都不能被 聲明為 static。從 PHP 5.3.0 起, 將這些魔術方法定義為 static 會產生一個警告。
樣本:
class a{ public function __set($name,$value){ //$this->data[$name]=$value; $this->$name=$value; } public function __get($name){ return $this->$name; } public function __isset($name){ return isset($this->$name); } public function __unset($name){ unset($this->$name); }}$obj_a=new a();$obj_a->first='first';echo $obj_a->first."
";echo isset($obj_a->second)?'second exist
':'second not exist
';echo isset($obj_a->first)?'first exist
':'first not exist
';echo empty($obj_a->first)?'first exist
':'first not exist
';unset($obj_a->first);echo isset($obj_a->first)?'first exist
':'first not exist
';
結果:
first
second not exist
first exist
first not exist
first not exist
方法重載
public mixed __call ( string $name , array $arguments )
public static mixed __callStatic ( string $name , array $arguments )
在對象中調用一個不可存取方法時,__call() 會被調用。
用靜態方式中調用一個不可存取方法時,__callStatic() 會被調用。
$name 參數是要調用的方法名稱。$arguments 參數是一個枚舉數組,包含著要傳遞給方法 $name 的參數。
樣本:
echo "";class a { public function __call($name,$arguments){ if($name=='mycall'){ print_r($arguments); call_user_func('mycall',$arguments[0],$arguments[1]); }else{ echo "call uknow function"; } }}function mycall($a1,$a2){ echo "this is mycall
"; print_r($a1); print_r($a2); echo "end of mycall
";}$obj_a=new a();$obj_a->mycall(['a'=>'aaa'],['a2'=>'a2']);$obj_a->notcall(); 結果:
Array( [0] => Array ( [a] => aaa ) [1] => Array ( [a2] => a2 ))this is mycallArray( [a] => aaa)Array( [a2] => a2)end of mycallcall uknow function
樣本:
echo "";class a { public static function __callStatic($name,$arguments){ if($name=='mycall'){ print_r($arguments); call_user_func('mycall',$arguments[0],$arguments[1]); }else{ echo "call uknow function"; } }}function mycall($a1,$a2){ echo "this is mycall
"; print_r($a1); print_r($a2); echo "end of mycall
";}$obj_a=new a();$obj_a::mycall(['a'=>'aaa'],['a2'=>'a2']);$obj_a::notcall(); 結果:
Array( [0] => Array ( [a] => aaa ) [1] => Array ( [a2] => a2 ))this is mycallArray( [a] => aaa)Array( [a2] => a2)end of mycallcall uknow function