• php 构造函数支持不同个数参数的方法


    php 构造函数支持不同个数参数方法

    原理:在__construct中使用 func_num_args 获取参数个数,再根据参数个数执行不同的调用。参数值使用func_get_arg() 方法获得。

    demo:

    <?php
    class demo{
     
        private $_args;
     
        public function __construct(){
            $args_num = func_num_args(); // 获取参数个数
     
            // 判断参数个数与类型
            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执行后输出:

    Array
    (
        [id] => 1
        [dname] => fdipzone
    )
    Array
    (
        [device] => Array
            (
                [0] => iOS
                [1] => Android
            )
     
    )
  • 相关阅读:
    爬虫(五):生产者消费者方法
    三. Anagram detection problem for string(字符串中回文词汇检测问题)
    二. Object-Oriented Programming in Python: Defining Classes
    一.Introduction
    爬虫(四):正则表达式(提取str中网址)
    centos7源代码编译安装heartbeat
    linux yum配置
    java常见证书类型和密钥库类型
    常用的加密算法
    iptables学习理解
  • 原文地址:https://www.cnblogs.com/saonian/p/9356093.html
Copyright © 2020-2023  润新知