PHP高级对象构建 多个构造函数的使用

yipeiwu_com5年前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类中private属性继承问题分析

请仔细看这句话 如果父类有私有的属性。那么父类的方法只为父类的私有属性服务。 下面通过一系列列子来加深理解. 这个例子看起来很奇怪,在子类中重新定义了一个属性$sal,系统却返回了父类的...

PHP简单生成缩略图相册的方法

本文实例讲述了PHP简单生成缩略图相册的方法。分享给大家供大家参考。具体如下: <?php /* * written by mot * 根目录下自己新建image...

PHP+jQuery实现双击修改table表格功能示例

PHP+jQuery实现双击修改table表格功能示例

本文实例讲述了PHP+jQuery实现双击修改table表格功能。分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"&...

PHP请求远程地址设置超时时间的解决方法

php请求远程地址设置超时时间,主要讲解file_get_contents、fopen、curl这三个简单常用函数设置超时时间的方法,一般情况下建议使用curl,性能最好,效率也最高。...

php下实现折线图效果的代码

<?php   Class ImageReport{  var $X;//图片大小X轴  var $Y;//图...