Direct method call in instance

Asked

Viewed 1,506 times

1

I came across something that doesn’t seem to make sense, when I try to make the method call from a direct object in its instance it doesn’t 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?

  • 3

    I believe that’s when you wear $eu = new Pessoa("Vinicius"); you are making a reference and when you simply use new Pessoa("Vinicius")->getNome(); you try to directly access the object and believe that this is not possible without a reference.

  • 2

    @Silvio according to the answers below this is a particularity of php because there is no such thing as accessing a method only by object reference.

  • 4

    I’m sorry, mistake failed.

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, it is possible to obtain a similar result by declaring a global function with the same class name, returning a new instance of this 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 absurd, that’s exactly what Laravel does from version 5 with its helpers to decrease verbosity in simple instance calls.

Reference

  • 2

    The solution proposed in PHP 5.4 is very elegant, but using a function with the same class name seems to me a size-less gambiarra :)

  • @Rodrigorigotti also agree that it is a size-less gambiarra... but since the language allows... rs

2

This is not possible in versions prior to PHP 5.4

Unfortunately you need to use the second form, but in newer versions simply add parentheses around your instance:

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

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();

0

Within the Construct you can return the class itself by creating a fluent interface.

In accordance with:

return $this;
  • What is the purpose of returning something in the constructor?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.