Oleg alex
Oleg alex

Reputation: 99

Method overloading doesn't work as expected

I have a method setAddress($town,$zip.$coord) defined in my class User. In the same class User I have the __call setter 'set' which is called when my method is called with only one parameter(ex: setAddress($town)). The problem is that when I call the method with one parameter : setAddress('New York'), I have an error('Missing parameters'). If i call it with 3 parameters the overloading is working. Why the __call function is not called if the method is called with 1 parameter?

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());

Upvotes: 0

Views: 54

Answers (1)

Jon
Jon

Reputation: 437336

The premise of the question is wrong: PHP, like most other dynamic languages, has no function overloading.

When you specify the name of a function that's what is going to get called; the number and types of the arguments do not play a part in the decision.

You can approximate the desired behavior by supplying default values for some arguments and checking the argument situation at runtime, e.g.:

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;
    }
}

Upvotes: 2

Related Questions