php函数重载与构造函数重载
来源:互联网 发布:linux中touch命令 编辑:程序博客网 时间:2024/05/19 05:39
<?php //函数重载
class
A
{
function
__call (
$name
,
$args
)
{
if
(
$name
==
'f'
)
{
$i
=
count
(
$args
);
if
(method_exists(
$this
,
$f
=
'f'
.
$i
)) { //检查类中是否存在该函数,this指调用该函数的对象
call_user_func_array(
array
(
$this
,
$f
),
$args
); //调用函数,array($this,$f)为要调用的函数名,$args为参数数组
}
}
}
function
f1(
$a1
)
{
echo
"1个参数"
.
$a1
.
"<br/>"
;
}
function
f2(
$a1
,
$a2
)
{
echo
"2个参数"
.
$a1
.
","
.
$a2
.
"<br/>"
;
}
function
f3(
$a1
,
$a2
,
$a3
)
{
echo
"3个参数"
.
$a1
.
","
.
$a2
.
","
.
$a3
.
"<br/>"
;
}
}
$a = new A;
$a->f('a');
$a->f('a','b');
$a->f('a','b','c');
$a->f('a');
$a->f('a','b');
$a->f('a','b','c');
?>
<?php //构造函数重载
class OverLoadTesting
{
public function __construct()
{
$num = func_num_args(); //获得参数个数
$args = func_get_args(); //获得参数列表数组
switch($num){
case 0:
$this->__call('__construct0', null);
break;
case 1:
$this->__call('__construct1', $args);
break;
case 2:
$this->__call('__construct2', $args);
break;
case 3:
$this->__call('__construct3', $args);
break;
default:
throw new Exception();
}
}
public function __construct0()
{
echo "constructor 0" . PHP_EOL;
}
public function __construct1($a)
{
echo "constructor 1: " . $a . PHP_EOL;
echo "<br/>";
}
public function __construct2($a,$b)
{
echo "constructor 2: " . $a ." ".$b." " . PHP_EOL;
var_dump($b);
}
public function __call($name, $arg) //根据函数名调用函数
{
return call_user_func_array(array($this, $name), $arg);
}
}
$a = new OverLoadTesting('a');
$b = new OverLoadTesting('a','b');
?>
php中的call_user_func_array的作用
一、直接调用方法function test($a, $b)
{
echo '测试一:'.$a.$b;
}
//调用test方法,array("asp", 'php')对应相应的参数
call_user_func_array('test', array("asp", 'php'));
二、通过类调用类中的方法
class test2{
function phpSay($a, $b)
{
echo '测试二:'.$a.$b;
}
}
$o = new test2();
//相当于:$o->phpSay('php','你好');
call_user_func_array(array(&$o, 'phpSay'), array('php','你好'));
0 0
- php函数重载与构造函数重载
- PHP重载构造函数
- PHP 构造函数的重载
- 构造函数,函数重载
- 函数的重载与构造函数
- JAVA的构造函数与函数重载
- 重载赋值函数与复制构造函数
- 构造函数重载
- C++构造函数重载
- 重载构造函数
- 构造函数 重载 好玩
- 构造函数重载
- 构造函数重载
- CDialog构造函数重载
- 构造函数重载
- 构造函数和重载
- 构造函数的重载
- c++构造函数重载
- JNDI 数据库连接池
- 中移动被央视炮轰抢劫是咎由自取
- SparkContext的parallelize的参数
- viewport mata 浏览器不再缩放
- 广度优先搜索
- php函数重载与构造函数重载
- 大数据系列教程_硬件配置及软件列表
- Android res文件夹
- C常见笔试题(一)
- hdu1520 Anniversary party(树形DP)
- 01背包,完全背包,多重背包详解
- 三星为何最烧包?没站在风口上?
- 后缀数组学习笔记【详解|图】
- 个人搭建博客