要实现一个构造函数是两个变量,另一个构造函数是一个数组。
如:public function construct($id, $dname)
public function construct($device=array())
在网上只搜到了,通过func_num_args判断参数个数实现,有通过判断类型实现的方法么?
在一个文件中不可能同时存在两个相同名字的方法函数
2.如果在不同文件中 可以用命名空间的方式实现相同函数的调用(php版本要 5.3.0 以上)
所以你的判断没有实在意义啊
php不能重载滴,把参数改成数组 在函数内区别吧
我想看看源代码它们是以什么形式并存的,继承?
gettype -- 获取变量的类型
construct 不是 php 类的构造函数
construct 才是!
虽然 php 不支持重载,但楼主也并没有说是在一个类中的同名方法
自己在构造函数construct中判断下参数类型,然后再走不同的分支就行了。不原生支持重载就模拟个嘛~
php 不向C一样不能支持函数重载,就像你说的通过func_num_arg函数然后判断参数来分支初始化嘛
可以在construct中判断参数个数与类型。<?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 '
';
print_r($this->_args);
echo '
';}
}
// demo1
$id = 1;
$dname = 'fdipzone';
$obj = new demo($id, $dname);
$obj->show();
// demo2
$device = array('iOS','Android');
$obj = new demo($device);
$obj->show();
?>