PHP advanced objects are used to build multiple constructors
- 2020-05-12 02:20:22
- OfStack
The following code example demonstrates the principle of using multiple constructors for object construction in PHP advanced object construction.
The above method shows how to use multiple constructors. In fact, it is very simple, mainly dealing with parameters, whether parameters are characters, or Numbers, or classes, all advanced different processing, so as to increase the flexibility of the code.
<?php
class classUtil {// This is a 1 A class that handles all parameters
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's an array, return "array"
if (is_numeric($var)) return "numeric";// If it's a number, return "numeric"
return "string";// String return "string"
}
public static function typelist($args){
return array_map(array("self","typeof"),$args);// The array loops through the call self::typeof To deal with $args Each element in
}
public static function callMethodForArgs($object,$args,$name="construct"){
$method=$name."_".implode("_",self::typelist($args));//implode I'm using array elements "_" Connection to 1 A string
if (!is_callable(array($object,$method))){//is_callable() Function test $object::$method Not 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 A function call $object::$method ( $args )
}
}
}
class dateAndTime {
private $timetamp;
public function __construct(){// Its own constructor
$args=func_get_args();// To obtain parameters
classUtil::callMethodForArgs($this,$args);// Calls the method of the parameter handler class
}
public function construct_(){// When the parameter is null
$this->timetamp=time();
}
public function construct_dateAndTime($datetime){// For the class itself
$this->timetamp=$datetime->getTimetamp();
}
public function construct_number($timestamp){// For the Numbers
$this->timetamp=$timestamp;
}
public function construct_string($string){// Is a time string
$this->timetamp=strtotime($string);
}
public function getTimetamp(){// Get the timestamp method
return $this->timetamp;
}
}
?>
The above method shows how to use multiple constructors. In fact, it is very simple, mainly dealing with parameters, whether parameters are characters, or Numbers, or classes, all advanced different processing, so as to increase the flexibility of the code.