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
)
)本篇介绍了关于php 构造函数支持不同个数参数的方法,更多相关内容请关注php中文网。
相关推荐:
立即学习“PHP免费学习笔记(深入)”;
以上就是关于php 构造函数支持不同个数参数的方法介绍的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号