Constructor returning value?

后端 未结 6 1604
北荒
北荒 2020-12-01 16:07

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?



        
6条回答
  •  猫巷女王i
    2020-12-01 16:14

    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;
    

提交回复
热议问题