方法重载无法按预期工作


Method overloading doesn't work as expected

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

用户.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');

    }


   }
}  

索引.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());

这个问题的前提是错误的: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;
    }
}