方法重载不能按预期工作

时间:2013-11-07 13:16:28

标签: php overloading

我的课程用户中定义了 setAddress($ town,$ zip。$ coord)方法。在同一个类User中我有 __ call setter'set',当我的方法只用一个参数调用时调用(例如:setAddress($ town))。问题是当我用一个参数调用方法时:setAddress('New York'),我有一个错误('缺少参数')。如果我用3个参数调用它,则重载正在起作用。如果使用1参数调用方法,为什么不调用__call函数?

user.php的

namespace com\killerphp\modells;
class User{
    protected $address;
    protected $firstName;
    protected $lastName;
    protected $email;

public function setAddress($town,$zip,$coord){
    echo "I have 3 arguments";
}
public function __call($name, $arguments) {
    $prefix=  substr($name, 0, 3); //get,set
    $property=substr($name, 3);    //address,firstName,email etc
    $property=lcfirst($property);

    switch($prefix){
        case "set":
            if(count($arguments)==1){
                echo 'asa i';
                $this->$property=$arguments[0];
            }

            break;
        case  "get":
            return $this->$property;
            break;
        default: throw new \Exception('magic method doesnt support the prefix');


    }





   }
}  

的index.php

    define('APPLICATION_PATH',  realpath('../'));
    $paths=array(
        APPLICATION_PATH,
        get_include_path()
    );
    set_include_path(implode(PATH_SEPARATOR,$paths));

    function __autoload($className){
        $filename=str_replace('\\',DIRECTORY_SEPARATOR , $className).'.php';
        require_once $filename; 
        }

    use com\killerphp\modells as Modells;
    $g=new Modells\User();
    $g->setAddress('new york','23444','west');
    echo($g->getAddress());

1 个答案:

答案 0 :(得分:2)

问题的前提是错误的:与大多数其他动态语言一样,PHP没有函数重载。

当您指定要调用的函数的名称时;参数的数量和类型在决策中不起作用。

您可以通过为某些参数提供默认值并在运行时检查参数情况来近似所需的行为,例如:

public function setAddress($town, $zip = null, $coord = null) {
    switch(func_num_args()) {
        // the following method calls refer to private methods that contain
        // the implementation; this method is just a dispatcher
        case 1: return $this->setAddressOneArg($town);
        case 3: return $this->setAddressThreeArgs($town, $zip, $coord);
        default:
            trigger_error("Wrong number of arguments", E_USER_WARNING);
            return null;
    }
}
相关问题