构造函数返回值? [英] Constructor returning value?

查看:131
本文介绍了构造函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的代码,我看到构造函数返回一个值。我认为构造函数只返回对象。有人能告诉我我失踪了什么?

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


推荐答案

你是对的。没有什么可以做一个构造函数的返回值(除了使用它创建的对象)。

Indeed you are correct. Nothing can be done with the return value of a constructor (aside from using the Object it created).

没有,你没有丢失任何东西,这是开发人员

So no, you aren't missing anything, it's the developer who wrote that code who is.

如果你直接调用函数,在技术上可以使用构造函数的返回值。

It is technically possible to use return values from constructors, if you call the function directly

$obj->__construct();

这将允许你使用构造函数的返回值。但是,这是非常罕见的,不太推荐。

That would allow you to use the constructor's return value. However, that is highly uncommon and fairly not recommended.

这篇关于构造函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆