Reputation: 166697
For learning purposes, is there any way of initializing an object, call its method and assign the object to the variable in one statement in PHP?
I've tried something like:
$dom = (new DOMDocument)->loadHTML('<html></html>');
echo gettype($dom); // Result: boolean
but it's returning boolean instead of the object, so I can't do anything with it.
I'm expecting to be an object, so I can call: $dom->saveHTML();
, but instead it's throwing the error:
Fatal error: Call to a member function saveHTML() on a non-object
Is there any workaround? Or these are the limits of the language.
The following code works correctly:
$dom = new DOMDocument;
$dom->loadHTML('<html></html>');
echo gettype($dom); // Result: object
I'm using PHP 5.5.3 (cli).
Upvotes: 1
Views: 175
Reputation: 14984
You cannot do it in the way it seems like you're wanting.
What you're trying to do (or so I believe) is assign new DOMDocument
to the $dom
variable AND call loadHTML('<html></html>')
in one line like:
//$boolval is just there for readability
$boolval = ($dom = (new DOMDocument))->loadHTML('<html></html>')
which will give you a T_OBJECT_OPERATOR
syntax error.
There is no way to write the above statement in one line like you're wanting (I don't have proof other than testing and experience).
Furthermore, one-lining your code is not always a great thing to do. It is often nice while you're writing the code initially, but can cause significant headaches later if you have any errors. Also if you want to update your code, since the one-line version of stuff is less understandable without comments, that could also become more difficult.
If you want to hackify it a little bit (waste resources and readability), then you could create a function where you pass by reference a variable (which will be set to the object), the object, and the function you want to call along with an array of paramaters.
The function would be something like:
function callAndSet(&$var,$object,$funcName,$argsArray=array()){
//instead of $argsArray, you could use a vararg ( use func_get_args()/array_slice() )
$var = $object;
call_user_func_array(array($object,$funcName),
$argsArray
);
}
then to use it:
callAndSet($dom,new DOMDocument(),'loadHTML',array('<html></html>'));
$dom->saveHTML()
Upvotes: 1
Reputation: 14310
What you are saying here is:
$dom = (new DOMDocument)->loadHTML('<html></html>');
DOMDocument
loadHTML
method on it$dom
So it all depends on what the method is returning. The doc clearly says that it returns a boolean (http://php.net/manual/en/domdocument.loadhtml.php), so that is what is getting stored in your variable.
In your own code, I believe it is good practice to add a return $this
at the end of your methods (unless they need to return something else obviously). If that where the case here, your first code example would work fine. Now you'll have to go with the second sample though...
Upvotes: 1