下面就用一段程式碼範例來示範一下PHP進階對象構建中的使用多個建構函式進行對象構建的原理。
複製代碼 代碼如下:
class classUtil {//這是一個參數處理的類
public static function typeof($var){
if (is_object($var)) return get_class($var);//如果是對象,擷取類名
if (is_array($var)) return "array";//如果是數組,返回"array"
if (is_numeric($var)) return "numeric";//如果是數字,返回"numeric"
return "string";//字串返回 "string"
}
public static function typelist($args){
return array_map(array("self","typeof"),$args);//數組迴圈通過調用self::typeof處理$args中的每個元素
}
public static function callMethodForArgs($object,$args,$name="construct"){
$method=$name."_".implode("_",self::typelist($args));//implode 是把數組元素用"_"串連成一個字串
if (!is_callable(array($object,$method))){//is_callable()函數測試$object::$method是不是可調用的結構
echo sprintf("Class %s has no methd '$name' that takes".
"arguments (%s)",get_class($object),implode(",",self::typelist($args)));
call_user_func_array(array($object,$method),$args);//call_user_func_array函數調用$object::$method($args)
}
}
}
class dateAndTime {
private $timetamp;
public function __construct(){//自身的建構函式
$args=func_get_args();//擷取參數
classUtil::callMethodForArgs($this,$args);//調用參數處理類的方法
}
public function construct_(){//參數為空白的時候
$this->timetamp=time();
}
public function construct_dateAndTime($datetime){//為類自身的時候
$this->timetamp=$datetime->getTimetamp();
}
public function construct_number($timestamp){//為數位時候
$this->timetamp=$timestamp;
}
public function construct_string($string){//為時間型字串時候
$this->timetamp=strtotime($string);
}
public function getTimetamp(){//擷取時間戳記的方法
return $this->timetamp;
}
}
?>
以上方法,就說明了多個建構函式的使用方法,其實,很簡單,主要是對參數進行了處理,不管是參數是字元,還是數字,還是類,都先進了不同的處理,這樣就加大了代碼的靈活性。
以上就介紹了建構函式 PHP進階對象構建 多個建構函式的使用,包括了建構函式方面的內容,希望對PHP教程有興趣的朋友有所協助。