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');
?>




<?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
原创粉丝点击