Heim > php教程 > php手册 > Hauptteil

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

WBOY
Freigeben: 2016-06-13 12:02:26
Original
769 Leute haben es durchsucht

下面就用一段代码示例来演示一下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;
}
}
?>


以上方法,就说明了多个构造函数的使用方法,其实,很简单,主要是对参数进行了处理,不管是参数是字符,还是数字,还是类,都先进了不同的处理,这样就加大了代码的灵活性。
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!