【问题标题】:Why this code throw syntax error unexpected in all function where i invoke more then one -> function [duplicate]为什么此代码在我调用多个函数的所有函数中引发语法错误->函数[重复]
【发布时间】:2020-03-11 15:36:36
【问题描述】:

为什么这段代码会抛出

语法错误,意外 '->' (T_OBJECT_OPERATOR),需要 ',' 或 ';'

php 7.1

<?php
class TestHtml
{
    public function Send() { return $this; }
    public function Dispose() { return $this; }
    public function ToString() { return 'Done'; }
}
echo new TestHtml->Send()->Dispose()->ToString(); // there error 
?>

【问题讨论】:

  • echo (new TestHtml())-&gt;Send()-&gt;Dispose()-&gt;ToString();
  • 更多的括号总是答案
  • 谢谢大家的好问题回答,这对我很有帮助

标签: php


【解决方案1】:

PHP 无法理解这一点。它无法弄清楚第一部分是对构造函数的调用。使用括号。

<?php
class TestHtml
{
    public function Send() { return $this; }
    public function Dispose() { return $this; }
    public function ToString() { return 'Done'; }
}
echo (new TestHtml)->Send()->Dispose()->ToString(); // there error 

或者,您可以先创建对象,然后调用其他函数。

$object = new TestHtml;
echo $object->Send()->Dispose()->ToString();

为了好玩,您可以创建一个静态函数来创建类。

<?php
class TestHtml
{
    public function Send() { return $this; }
    public function Dispose() { return $this; }
    public function ToString() { return 'Done'; }
    public static function make() { return new self; }
}
echo TestHtml::make()->Send()->Dispose()->ToString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 2011-01-24
    • 2015-03-23
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多