The "return new..." is just a subset of the problem, but not
the only one that is in wide use. For example, this is very common:function &getstuff($in)
{
if ($in=='ok')
return new MyObject();
else
return false; // this is the common line
}The "false" obviously is not a variable that can be reference
and it's even not an object, the technically more correct
answer would be "return null;". But both ways of doing it are
are not the "new ..." problem AND throw a notice AND PHP
should be able to silently know what to do. Boxing is an
approach that covers all of the similar problems and I think
it could easily be realizedsince I suppose PHP is already
doing something similar to fix the memory leak problems.
Of course you're right. Seems my view was a little biased from looking
at my code only ;). The "return new" issue has the interesting side
effect that notices disappear depending on the constructor's
implementation details.
Many people will agree that your above code should work - when seen from
the "conceptual" point of view. It's a nasty side effect that because of
the way the PHP4 internals worked, you had to use the reference here.
Note that the following is yet another way of stating the same:
function &getstuff($in) {
return ($in == 'ok' ? new MyObject() : null);
}
The problem is that even if internally temp assignments are used to make
it "still work", how to separate the cases where notices are appropriate
("bad code") from those where they are not (because everything was
"legal")?
[Weak point - others will throw in that it has never been "legal" but
"only worked" :)]
I don't understand the "only on PHP4": Why should PHP4 be
more "advanced" than PHP5 regarding this issue? And more
important: Why should the two versions differ in behaviour in
such a basic point?
With PHP5 object handles, passing around references is really rare. If
you ported your code to make use of the new PHP5 features, you probably
won't see the whole reference passing-related problems at all (at least
not in places where you're only doing correct OO stuff).
Your example with PHP5:
#!/usr/bin/php5
<?php
class Factory {
function build($what) {
if ($what == 'a')
return new Foo();
else
return null;
}
}
class Foo {
}
var_dump($x = Factory::build('a'));
var_dump($y = Factory::build('b'));
?>
gives:
object(Foo)#1 (0) {
}
NULL
Just as one would expect.
Matthias