0

I am confused, I have a PHP class with a constructor:

class Test {
   public function __construct() {
      return "some text";
   }
}

Then I instanciate an object:

$t = new Test();

I would expect the contents of $t to be "some text":

print_r($t);

But it is:

Test Object
(
)

How do I get the returned value "some text" from the constructor?

3
  • "some test" isn't stored anywhere and is lost as soon as the constructer is done running Commented May 24, 2012 at 1:58
  • You don't. Constructor only returns an instance Commented May 24, 2012 at 1:58
  • 2
    possible duplicate of returning a value in constructor function of a class, PHP Commented May 24, 2012 at 1:59

1 Answer 1

3

You cannot return anything from a constructor. The new keyword will always result in a new object, it does not matter what you return from the constructor.

Sign up to request clarification or add additional context in comments.

2 Comments

So if I want to return an error case in the constructor how is that done?
If you want to prevent the object from being instantiated, throw an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.