Methods for PHP constructors to support different number of parameters

Source: Internet
Author: User
Tags dname php class

PHP constructors support different number of parameter methods

Principle: Use Func_num_args to get the number of parameters in __construct, and then perform different calls based on the number of parameters. Parameter values are obtained using the Func_get_arg () method.

Demo

<?php class demo{Private $_args; Public Function __construct () {$args _num = Func_num_args ();//Get the number of arguments//determine the number of parameters and type if ($args _num==2)  
                                {$this->_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 ' <pre> ';  
        Print_r ($this->_args);  
    Echo ' </pre> ';  
}//Demo1 $id = 1;  
$dname = ' Fdipzone ';  
$obj = new Demo ($id, $dname);  
      
$obj->show (); Demo2 $device = Array (' IOS ', ' Android ');  
$obj = new Demo ($device);  
$obj->show (); ?>

Demo Output after execution:

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

Author: csdn blog proud Snow star Maple

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.