EDIT: Please note that I am appending my original question with my actual question due to realizing that I asked the wrong question (by forgetting what I actually meant to ask).
In PHP 5.4 (as of RC1), it is possible to access class methods on class instantiation.
In other words, as I understand it, it is now possible to do: $foo = new bar()->foobar(); which saves times and lines of code.
For my question, let’s look at the following example:
class foo {
function __construct() {
}
function bar() {
return 'world';
}
}
$foobar = (new foo())->bar();
echo $foobar;
My question is, in such a case, when both the constructor and the method that is called upon initialization return a value, what is output by the final line (i.e. echo $foobar;)?
If I had to guess, since I haven’t actually had a chance to play around with 5.4 yet, the return from foo::bar() would overwrite the return from foo::__construct() because it is returned last. But I just wanted to check.
Okay, so the above question is not even logical (since __construct() should not return). What I really meant to ask is this:
Does $foobar in the above example contain the class instance or the return from $bar? If the latter, what sense does it make to use this if the class will not be available after instantiated? Wouldn’t it be better to just use a static method or call the method on its own line?
First of all, you should never return anything from a constructor. Thats a basic rule. Now some of us don’t follow this because they like the concept of calling their constructor afterwards and receiving some input instead of nothing.
But in the case of a good programming strategy, a constructor should be called only via the “new” keyword and shouldn’t return anything.
And yes, in all cases, NEW CLASSNAME() returns the instanciated object in all cases 🙂
Happy programming…
Will output
EDIT following question change
My educated guess is that $foobar will contain “world” and thus echo it with your code.
Same thing occurs in other languages such as in c#. You can instanciate an object call a method directly inline and lose the object only to get the return from the inline function called.