Constructor returning value?

后端 未结 6 1602
北荒
北荒 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条回答
  •  长情又很酷
    2020-12-01 16:24

    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.

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

提交回复
热议问题