dongxiezhuo8852 2015-02-22 00:09
浏览 78

如何初始化一个对象,调用它的方法并在一个语句中赋值给变量?

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).

  • 写回答

2条回答 默认 最新

  • dongxinjun3944 2015-02-22 00:41
    关注

    What you are saying here is:

    $dom = (new DOMDocument)->loadHTML('<html></html>');
    
    • Create a new DOMDocument
    • call the loadHTML method on it
    • store the result of that method in a variable $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...

    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私