Home > Backend Development > PHP Tutorial > Share the method of constructor function in php supporting different number of parameters

Share the method of constructor function in php supporting different number of parameters

黄舟
Release: 2023-03-12 10:20:01
Original
1458 people have browsed it

php Constructor functionSupports different number of parameter methods

Principle: In construct Use func_num_args to get the number of parameters, and then perform different calls based on the number of parameters. The parameter value is obtained using the func_get_arg() method.

demo:

<?php
class demo{

    private $_args;

    public function construct(){
        $args_num = func_num_args(); // 获取参数个数

        // 判断参数个数与类型
        if($args_num==2){
            $this->_args = array(
                                &#39;id&#39; => func_get_arg(0),
                                &#39;dname&#39; => func_get_arg(1)
                            );
        }elseif($args_num==1 && is_array(func_get_arg(0))){
            $this->_args = array(
                                &#39;device&#39;=>func_get_arg(0)
                            );
        }else{
            exit(&#39;func param not match&#39;);
        }    
    }

    public function show(){
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        print_r($this->_args);
        echo &#39;
'; } } // demo1 $id = 1; $dname = 'fdipzone'; $obj = new demo($id, $dname); $obj->show(); // demo2 $device = array('iOS','Android'); $obj = new demo($device); $obj->show(); ?>
Copy after login


Output after demo execution:

Array
(
    [id] => 1
    [dname] => fdipzone
)
Array
(
    [device] => Array
        (
            [0] => iOS
            [1] => Android
        )

)
Copy after login

The above is the detailed content of Share the method of constructor function in php supporting different number of parameters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template