欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP高級對象構(gòu)建 多個構(gòu)造函數(shù)的使用

 更新時間:2012年02月05日 23:49:30   作者:  
構(gòu)建對象是PHP面向?qū)ο缶幊淘O(shè)計中的一個重要主題。在最簡單的情況下,普通構(gòu)造函數(shù)就夠用了,但如果要開展更為復(fù)雜的設(shè)計,那么構(gòu)造函數(shù)可能會變的難以管理
下面就用一段代碼示例來演示一下PHP高級對象構(gòu)建中的使用多個構(gòu)造函數(shù)進行對象構(gòu)建的原理。
復(fù)制代碼 代碼如下:

<?php
class classUtil {//這是一個參數(shù)處理的類
public static function typeof($var){
if (is_object($var)) return get_class($var);//如果是對象,獲取類名
if (is_array($var)) return "array";//如果是數(shù)組,返回"array"
if (is_numeric($var)) return "numeric";//如果是數(shù)字,返回"numeric"
return "string";//字符串返回 "string"
}
public static function typelist($args){
return array_map(array("self","typeof"),$args);//數(shù)組循環(huán)通過調(diào)用self::typeof處理$args中的每個元素
}
public static function callMethodForArgs($object,$args,$name="construct"){
$method=$name."_".implode("_",self::typelist($args));//implode 是把數(shù)組元素用"_"連接成一個字符串
if (!is_callable(array($object,$method))){//is_callable()函數(shù)測試$object::$method是不是可調(diào)用的結(jié)構(gòu)
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函數(shù)調(diào)用$object::$method($args)
}
}
}
class dateAndTime {
private $timetamp;
public function __construct(){//自身的構(gòu)造函數(shù)
$args=func_get_args();//獲取參數(shù)
classUtil::callMethodForArgs($this,$args);//調(diào)用參數(shù)處理類的方法
}
public function construct_(){//參數(shù)為空的時候
$this->timetamp=time();
}
public function construct_dateAndTime($datetime){//為類自身的時候
$this->timetamp=$datetime->getTimetamp();
}
public function construct_number($timestamp){//為數(shù)字的時候
$this->timetamp=$timestamp;
}
public function construct_string($string){//為時間型字符串時候
$this->timetamp=strtotime($string);
}
public function getTimetamp(){//獲取時間戳的方法
return $this->timetamp;
}
}
?>

以上方法,就說明了多個構(gòu)造函數(shù)的使用方法,其實,很簡單,主要是對參數(shù)進行了處理,不管是參數(shù)是字符,還是數(shù)字,還是類,都先進了不同的處理,這樣就加大了代碼的靈活性。

相關(guān)文章

最新評論