Here's a code example to illustrate the principle of using multiple constructors to build objects in a PHP advanced object build.
Copy Code code as follows:
<?php
Class Classutil {//This is a handler for a parameter
public static function typeof ($var) {
if (Is_object ($var)) return Get_class ($var);//If object, get class name
if (Is_array ($var)) return "array";//if is an array, returns "Array"
if (Is_numeric ($var)) return "numeric";//if it's a number, go back to "numeric"
Return "string";//String returns "string"
}
public static function Typelist ($args) {
return Array_map (Array ("Self", "typeof"), $args);//array loop handles each element of $args by calling Self::typeof
}
public static function Callmethodforargs ($object, $args, $name = "construct") {
$method = $name. " _ ". Implode (" _ ", Self::typelist ($args));//implode is to concatenate the array elements with" _ "into a string
if (!is_callable ($object, $method)) {//is_callable () function test $object:: $method is not a callable struct
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 () {//Self constructor
$args =func_get_args ()//Get Parameters
Classutil::callmethodforargs ($this, $args);//calling methods for parameter-handling classes
}
When the public function construct_ () {//parameter is empty
$this->timetamp=time ();
}
When public function Construct_dateandtime ($datetime) {//Is the class itself
$this->timetamp= $datetime->gettimetamp ();
}
When the public function Construct_number ($timestamp) {//is a number
$this->timetamp= $timestamp;
}
Public Function construct_string ($string) {//Is time-type string
$this->timetamp=strtotime ($string);
}
Public Function Gettimetamp () {//Get timestamp method
return $this->timetamp;
}
}
?>
The above method, explained the use of several constructors, in fact, very simple, mainly to the parameters of the processing, whether the parameters are characters, or numbers, or classes, are advanced different processing, which increases the flexibility of the code.