The following uses a code example to demonstrate how PHP advanced object construction uses multiple constructors to build objects.
Copy codeThe Code is as follows: <? Php
Class classUtil {// This is a class for parameter processing.
Public static function typeof ($ var ){
If (is_object ($ var) return get_class ($ var); // if it is an object, obtain 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 return "string"
}
Public static function typelist ($ args ){
Return array_map (array ("self", "typeof"), $ args); // The array loops by calling self: typeof to process each element in $ args
}
Public static function callMethodForArgs ($ object, $ args, $ name = "construct "){
$ Method = $ name. "_". implode ("_", self: typelist ($ args); // implode concatenates an array element into a string using "_"
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
$ Args = func_get_args (); // obtain the Parameter
ClassUtil: callMethodForArgs ($ this, $ args); // call the method of the parameter processing class
}
Public function construct _ () {// when the parameter is null
$ This-> timetamp = time ();
}
Public function construct_dateAndTime ($ datetime) {// when the class itself is
$ This-> timetamp = $ datetime-> getTimetamp ();
}
Public function construct_number ($ timestamp) {// when the value is a number
$ This-> timetamp = $ timestamp;
}
Public function construct_string ($ string) {// when it is a time string
$ This-> timetamp = strtotime ($ string );
}
Public function getTimetamp () {// method for obtaining the timestamp
Return $ this-> timetamp;
}
}
?>
The above method illustrates how to use multiple constructor functions. In fact, it is very simple, mainly to process parameters, whether the parameters are characters, numbers, or classes, different processing methods are advanced, which increases the flexibility of the Code.