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

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

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

<?php
class classUtil {//這是一個(gè)參數(shù)處理的類
public static function typeof($var){
if (is_object($var)) return get_class($var);//如果是對(duì)象,獲取類名
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)通過(guò)調(diào)用self::typeof處理$args中的每個(gè)元素
}
public static function callMethodForArgs($object,$args,$name="construct"){
$method=$name."_".implode("_",self::typelist($args));//implode 是把數(shù)組元素用"_"連接成一個(gè)字符串
if (!is_callable(array($object,$method))){//is_callable()函數(shù)測(cè)試$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ù)為空的時(shí)候
$this->timetamp=time();
}
public function construct_dateAndTime($datetime){//為類自身的時(shí)候
$this->timetamp=$datetime->getTimetamp();
}
public function construct_number($timestamp){//為數(shù)字的時(shí)候
$this->timetamp=$timestamp;
}
public function construct_string($string){//為時(shí)間型字符串時(shí)候
$this->timetamp=strtotime($string);
}
public function getTimetamp(){//獲取時(shí)間戳的方法
return $this->timetamp;
}
}
?>

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

相關(guān)文章

最新評(píng)論