Here's a code example to illustrate the principle of using multiple constructors for object building in PHP advanced object building.
Copy the Code code as follows:
Class Classutil {//This is a parameter handler
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 ("Self", "typeof"), $args);//array loops process each element in the $args by calling Self::typeof
}
public static function Callmethodforargs ($object, $args, $name = "construct") {
$method = $name. " _ ". Implode (" _ ", Self::typelist ($args));//implode is to concatenate an array element with" _ "into a string
if (!is_callable (Array ($object, $method))) {//is_callable () function test $object:: $method is 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 function call $object:: $method ($args)
}
}
}
Class DateAndTime {
Private $timetamp;
Public Function __construct () {//constructor for itself
$args =func_get_args ();//Get Parameters
Classutil::callmethodforargs ($this, $args);//methods for invoking parameter processing classes
}
Public Function construct_ () {///parameter is empty
$this->timetamp=time ();
}
Public Function Construct_dateandtime ($datetime) {//For the class itself
$this->timetamp= $datetime->gettimetamp ();
}
Public Function Construct_number ($timestamp) {//is a number when
$this->timetamp= $timestamp;
}
Public Function construct_string ($string) {//is a time-type string
$this->timetamp=strtotime ($string);
}
Public Function Gettimetamp () {//method to get timestamp
return $this->timetamp;
}
}
?>
The above method, explains the use of multiple constructors, in fact, is very simple, the main parameter is processed, regardless of whether the parameters are characters, or numbers, or classes, are advanced different processing, thus increasing the flexibility of the code.
The above describes the construction of PHP high-level object construction of the use of multiple constructors, including the content of the constructor, I hope that the PHP tutorial interested in a friend to help.