0

クラスUserでメソッドsetAddress($town,$zip.$coord)を定義しています。同じクラス User に、メソッドが 1 つのパラメーター (例: setAddress($town)) だけで呼び出されたときに呼び出される__callセッター 'set' があります。問題は、setAddress('New York') という 1 つのパラメーターを使用してメソッドを呼び出すと、エラー ('Missing parameters') が発生することです。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());
4

1 に答える 1

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;
    }
}
于 2013-11-07T13:18:13.993 に答える