0

Why this code throw

syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting ',' or ';'

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 
?>
TipEra
  • 159
  • 6

1 Answers1

1

PHP cannot make sense of this. It cannot figure out that the first part is a call to a constructor. Use parens.

<?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 

Alternatively, you could create the object first, then call the other functions.

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

And just for fun, you could make a static function to create the class.

<?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();
ryantxr
  • 4,119
  • 1
  • 11
  • 25