Home >Backend Development >PHP Tutorial >Constructor PHP advanced object construction The use of multiple constructors
The following is a code example to demonstrate the principle of using multiple constructors for object construction in PHP advanced object construction.
Copy the code The code is as follows:
class classUtil {//This is a parameter processing class
public static function typeof($var){
if (is_object($var)) return get_class($var);//If it is an object, get the class name
if (is_array($var)) return "array";//If it is an array, return "array"
if (is_numeric($var)) return "numeric";//If it is a number, return "numeric"
return "string";//String returns "string"
}
public static function typelist($args){
return array_map(array("self", "typeof"),$args);//The array loop processes each element in $args by calling self::typeof
}
public static function callMethodForArgs($object,$args,$name="construct"){
$method=$name."_".implode("_",self::typelist($args));//implode is to use "_" to connect the array elements into a string
if (!is_callable(array( $object,$method))){//is_callable() function tests whether $object::$method is a callable structure
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 function call $object::$method($args)
}
}
}
class dateAndTime {
private $timetamp;
public function __construct(){//own constructor
$args=func_get_args();//get parameters
classUtil::callMethodForArgs($this,$args);//Call the method of parameter processing class
}
public function construct_(){//When the parameter is empty
$this->timetamp=time();
}
public function construct_dateAndTime($datetime){//When it is the class itself
$this->timetamp=$datetime->getTimetamp();
}
public function construct_number($timestamp){//It is a number When
$this->timetamp=$timestamp;
}
public function construct_string($string){//When it is a time string
$this->timetamp=strtotime($string);
}
public function getTimetamp(){//Method to get timestamp
return $this->timetamp;
}
}
?>
The above introduces the constructor function, PHP advanced object construction, and the use of multiple constructors, including the content of constructor functions. I hope it will be helpful to friends who are interested in PHP tutorials.