Reputation:
I noticed that constructors in PHP classes cannot return a value other than objects when implicitly called from outside of the class:
class A
{
function __construct ()
{
return FALSE;
}
function aFunctionInside ()
{
$aVar = $this->__construct ();
echo gettype($aVar);
}
}
$A = new A;
$A->aFunctionInside (); // boolean
echo gettype ($A); //object
Is this behavior helpful in any case?
Upvotes: 1
Views: 76
Reputation: 350290
A constructor is implicitly called when an object is created (with new
). However, its return value is not used in that case, and has nothing to do with the object that is being created.
It is not the constructor that creates the object, because even without one, an object would be created anyway. What's more, when the constructor runs, the object is already there.
No return value is expected from a constructor. According to the manual it has no return type:
Constructor
void __construct ([ mixed $args = "" [, $... ]] )
You are of course free to return something and use that when you call that function explicitly, as with any other function, but don't expect that call to create another instantiation of your class. For that you need to use the new
syntax.
The return value plays no role when it is called implicitly during object creation: the return value is ignored in that case.
Upvotes: 1