Returning a value in constructor function of a class

后端 未结 8 588
情话喂你
情话喂你 2020-11-27 17:04

So far I have a PHP class with the constructor

public function __construct ($identifier = NULL)
{
 // Return me.
if ( $identifier != NULL )
{
           


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 17:34

    Why not simply pass the results into the constructor needed to build the object, rather than try to make the constructor fail sometimes?

    Even if you could make it fail sometimes, you will still need to check after calling the constructor to ensure it actually did construct, and in those lines, you could just call the ->loadUser() and pass the results into the constructor.

    A good hint someone one told me, "always give the constructor what it needs to build the object, don't make it go looking for it."

    public function __construct ($emailInTheDatabase, $otherFieldNeeded)
    {
        $this->emailAddress = $emailInTheDatabase;
        $this->otherField = $otherFieldNeeded;
    }
    

提交回复
热议问题