php 构造函数返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11904255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:25:33  来源:igfitidea点击:

Constructor returning value?

phpconstructorreturn

提问by Nate

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

回答by Madara's Ghost

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.

这将允许您使用构造函数的返回值。然而,这是非常不常见的,也不推荐。

回答by Vladimir Kornea

The answers given so far are incorrect. You can do whatever you want with the return value of a constructor, so it's not true that "Nothing can be done with the return value of a constructor (aside from using the Object it created)." The return value of a constructor is not the object "it" created. The constructor does not create objects (the newkeyword does). The return value of a constructor is the same as that of any other function: whatever you choose to return. Further, it is also false that an object already has to exist in order to call its constructor. This is perfectly valid:

到目前为止给出的答案是不正确的。你可以对构造函数的返回值做任何你想做的事情,所以“构造函数的返回值不能做任何事情(除了使用它创建的对象)”是不正确的。构造函数的返回值不是“它”创建的对象。构造函数不会创建对象(new关键字会)。构造函数的返回值与任何其他函数的返回值相同:无论您选择返回什么。此外,为了调用其构造函数,对象已经存在也是错误的。这是完全有效的:

$parent_constructor_return_value = parent::__construct();

For example:

例如:

abstract class MyBase {
    function __construct () {
        return "Hello, world.";
    }
}
class MyDerived extends MyBase {
    function __construct () {
        echo parent::__construct();
    }
}
new MyDerived(); // prints "Hello, world."

While this is possible, I can't conceive of a scenario in which it would be best practice. After all, you could always call a method other than parent::__construct()to get your value, and all you lose is obscurity. I suppose it could be used as a way of error-handling--there are two other ways to accomplish the same thing:

虽然这是可能的,但我无法想象这是最佳实践的场景。毕竟,你总是可以调用一个方法而不是parent::__construct()获取你的值,而你失去的只是默默无闻。我想它可以用作错误处理的一种方式——还有另外两种方法可以完成同样的事情:

  1. Throw Exceptions in the parent constructor and catch them in your derived constructor.
  2. Set properties in the parent constructor indicating that an error happened, and then check the state of those properties in the derived constructor.
  1. 在父构造函数中抛出异常并在派生构造函数中捕获它们。
  2. 在父构造函数中设置指示发生错误的属性,然后在派生构造函数中检查这些属性的状态。

If an error in a parent constructor is not exceptional, he might have decided to have the parent constructor return error values, rather than storing transient error information as object properties. Of course, then the only reason to name the parent's method __constructis if the parent class is not abstract but can itself be instantiated--but in that context, the returned error messages would never be seen. So, bad pattern; bad. Constructors are not intended to return values, which means you're opening an architectural can of worms by leveraging this mechanism.

如果父构造函数中的错误不是例外,他可能决定让父构造函数返回错误值,而不是将瞬态错误信息存储为对象属性。当然,命名父方法的唯一原因__construct是父类不是抽象的,而是本身可以被实例化——但在这种情况下,将永远不会看到返回的错误消息。所以,糟糕的模式;坏的。构造函数不打算返回值,这意味着您正在通过利用此机制打开蠕虫的体系结构罐。

回答by Abid Hussain

see this url - Returning a value in constructor function of a class

看到这个 url -在类的构造函数中返回一个值

Read it:-

阅读:-

Constructors don't get return values; they serve entirely to instantiate the class.

构造函数没有返回值;它们完全用于实例化类。

Without restructuring what you are already doing, you may consider using an exception here.

如果不重构您已经在做的事情,您可以考虑在此处使用异常。

public function __construct ($identifier = NULL)
{
  $this->emailAddress = $identifier;
  $this->loadUser();
}

private function loadUser ()
{
    // try to load the user
    if (/* not able to load user */) {
        throw new Exception('Unable to load user using identifier: ' . $this->identifier);
    }
}

Now, you can create a new user in this fashion.

现在,您可以以这种方式创建一个新用户。

try {
    $user = new User('[email protected]');
} catch (Exception $e) {
    // unable to create the user using that id, handle the exception
}

回答by Peter Kiss

A constructor returns nothing, but you can return from it (stopping the method execution at a point for some reason but the object can be created).

构造函数不返回任何内容,但您可以从中返回(由于某种原因在某个点停止方法执行,但可以创建对象)。

回答by cleong

Unlike in other languages, in PHP you can explicitly call the constructor. It's just another function. It looks like the original author first decided to put some code that could fail in the constructor, then realized that he needs a way to rerun the initialization after a failure.

与其他语言不同,在 PHP 中您可以显式调用构造函数。这只是另一个功能。看起来原作者首先决定将一些可能会失败的代码放在构造函数中,然后意识到他需要一种在失败后重新运行初始化的方法。

$result = $user->__construct($username, $password)

would actually work and you do get the return value. It's an ugly way to do things obviously.

实际上会起作用并且您确实获得了返回值。显然,这是一种丑陋的做事方式。

In my opinion, it's not a good practice to have code that trigger side effects in the constructor. I would put the code in a separate function, with a name that clearly states what it does.

在我看来,在构造函数中使用触发副作用的代码不是一个好习惯。我会将代码放在一个单独的函数中,其名称清楚地说明了它的作用。

回答by Emad Ha

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..

如果您总是期望字符串作为返回值,您可以添加该方法,__toString()然后如果您尝试打印该类,它将返回您放置在那里的内容,只有字符串,我可以看到这是您的情况,所以我相信那应该对你有用..

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;