Direct method call on the instance

1

I came across something that does not seem to make sense, when I try to call the method of a direct object in its instance it does not seem to work.

class Pessoa{
        private $Nome;
        private $Idade;
        public function __construct($nome){
            $this->Nome = $nome;
        }
        public function getNome(){
            return $this->Nome;
        }
}

print new Pessoa("Vinicius")->getNome();
  

Parse error: syntax error, unexpected T_OBJECT_OPERATOR

However when I use a variable to reference the object the call works

$eu = new Pessoa("Vinicius");
print $eu->getNome();

Is there an error in the syntax of the first example?

    
asked by anonymous 26.03.2014 / 13:49

4 answers

6

PHP > = 5.4

From PHP 5.4 you can do the following:

print (new Pessoa("Vinicius"))->getNome();

PHP < 5.4

For versions prior to 5.4, you can get a similar result by declaring a global function with the same class name, returning a new instance of that class.

class Pessoa{
        private $Nome;
        private $Idade;
        public function __construct($nome){
            $this->Nome = $nome;
        }
        public function getNome(){
            return $this->Nome;
        }
}

function Pessoa($nome){
    return new Pessoa($nome);
}


print Pessoa("Vinicius")->getNome();

Although the second method seems to be absurd, this is exactly what Laravel does from version 5 with its helpers to reduce verbosity in simple instance calls.

Reference

    
26.03.2014 / 13:58
2

This is not possible in versions prior to PHP 5.4

Unfortunately you need to use the second form, however in newer versions you would just need to add parentheses around your instance:

print (new Pessoa("Vinicius"))->getNome();
    
26.03.2014 / 13:59
2

This functionality, Class member access on instantiation , is only available in version 5.4 or higher of php. Your code should look like this:

echo (new Pessoa('Vinicius'))->getNome();
    
26.03.2014 / 14:03
0

Inside the construct you can return the class itself by creating a fluent interface.

According to:

return $this;
    
25.04.2014 / 18:03