一起源码网

  • www.171739.xyz
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 3527|回复: 1
打印 上一主题 下一主题

php中构造函数支持不同个数参数的方法分享

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-3-17 02:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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
        )

)

分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

14

帖子

48

积分

等待验证会员

积分
48
沙发
发表于 2022-9-8 09:05 | 只看该作者
如何用源代码下载文件
回复

使用道具 举报

一起源码让程序更轻更快

www.171739.xyz

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表