PHP高级对象构建 多个构造函数的使用
PHP高级对象构建 多个构造函数的使用
发布时间:2016-12-29 来源:查字典编辑
摘要:下面就用一段代码示例来演示一下PHP高级对象构建中的使用多个构造函数进行对象构建的原理。复制代码代码如下:

下面就用一段代码示例来演示一下PHP高级对象构建中的使用多个构造函数进行对象构建的原理。

复制代码 代码如下:

<?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教程学习
编程开发子分类