Constructor returning value?

Viewed 42512

Looking at the following code, I see the constructor is returning a value. I thought that constructors only return objects. Can someone tell me what am I missing?

public function __construct($username = null, $password = null){
        $urlLogin = "{$this->apiHost}/login/$username";

        $postData = sprintf("api_type=json&user=%s&passwd=%s",
                            $username,
                            $password);
        $response = $this->runCurl($urlLogin, $postData);

        if (count($response->json->errors) > 0){
            return "login error";    
        } else {
            $this->modHash = $response->json->data->modhash;   
            $this->session = $response->json->data->cookie;
            return $this->modHash;
        }
    }
6 Answers

If you're always expecting a string as a return value you can add the method __toString() then if you try to print that class it will return what you placed in there, only strings, and i can see that it's your case here, so i believe that should work for you..

public function __construct($username = null, $password = null){
    $urlLogin = "{$this->apiHost}/login/$username";

    $postData = sprintf("api_type=json&user=%s&passwd=%s",
                        $username,
                        $password);
    $response = $this->runCurl($urlLogin, $postData);

    if (count($response->json->errors) > 0){
        return "login error";    
    } else {
        $this->modHash = $response->json->data->modhash;   
        $this->session = $response->json->data->cookie;
        return $this->modHash;
    }
}

public function __toString(){
     return $this->modeHash;   
}

...
echo yourClass($username, $password); // will return yourClass->modeHash;
Related