简体   繁体   中英

Method Chaining and the new Keyword returning error in PHP 5.4.x

I was trying to chain the following code below into 1 line. Purely for experimentation to see if it could be done.

This is the original code, which works:

$dom = new DomDocument();
$dom->loadHtml($html);
$xpath = new DomXPath($dom);

But, when chaining, this returns an error:

$xpath = new DomXPath((new DomDocument())->loadHtml($html));

The error is:

Catchable fatal error: Argument 1 passed to DOMXPath::__construct() must be an instance of DOMDocument, boolean given

If this sort of chaining is allowed in PHP 5.4.x the why does it not work as expected?

The error actually said it just perfeclly: loadHtml returned a Bool (true/false). Check the manual for the return value.

Error: Catchable fatal error: Argument 1 passed to DOMXPath::__construct() must be an instance of DOMDocument, boolean given

Code:

$xpath = new DomXPath((new DomDocument())->loadHtml($html));
//                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                     Argument 1, that returned a bool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM