建構函式 PHP進階對象構建 多個建構函式的使用

來源:互聯網
上載者:User
下面就用一段程式碼範例來示範一下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教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.