Home>Article>Backend Development> An introduction to how the PHP constructor supports different numbers of parameters
php constructor supports different number of parameter methods
Principle:Use in __constructfunc_num_argsGet the number of parameters, and then execute different calls based on the number of parameters. The parameter value is obtained using thefunc_get_arg()method.
demo:
_args = array( 'id' => func_get_arg(0), 'dname' => func_get_arg(1) ); }elseif($args_num==1 && is_array(func_get_arg(0))){ $this->_args = array( 'device'=>func_get_arg(0) ); }else{ exit('func param not match'); } } public function show(){ echo ''; print_r($this->_args); echo ''; } } // demo1 $id = 1; $dname = 'fdipzone'; $obj = new demo($id, $dname); $obj->show(); // demo2 $device = array('iOS','Android'); $obj = new demo($device); $obj->show(); ?>
Output after demo execution:Array ( [id] => 1 [dname] => fdipzone ) Array ( [device] => Array ( [0] => iOS [1] => Android ) )This article introduces how the PHP constructor supports different numbers of parameters. For more related content, please pay attention to the PHP Chinese website.
Related recommendations:
How to use PDO to query mysql to avoid SQL injection
Explanation of the PHP two-way queue class
The differences and characteristics between php heredoc and nowdoc
The above is the detailed content of An introduction to how the PHP constructor supports different numbers of parameters. For more information, please follow other related articles on the PHP Chinese website!