Leff Leff - 1 year ago 95
PHP Question

Laravel calling model after declaring function with colon

I was reading a short tutorial on Laravel here. Since I am not experienced in laravel or development in general I am wondering what this part of the code does exactly:

public function approve(): User

As it is seems to me, it is the same thing as just calling the model from inside the function like so:


What is the difference in this two approches?

Answer Source

No, they're not the same. The first code is utilizing PHP 7's return type declerations.

It says that the method must return an instance of User class, or PHP will throw a TypeError for you. You can also specify the FQN of the class when defining return type declarations:

public function approve(): \App\User

It's specially useful when defining interfaces:

interface CommentsIterator extends Iterator {
    function current(): Comment; 
    // This enforces that any implementation of current() 
    // method, must return an instance of Comment class.

See what other RFCs made their way into PHP 7:

And treat yourself with Jeffrey's screencasts on PHP 7 new features:

But the second code (App\User::whatever()) is just calling the static method whatever() of the App\User class. It has nothing to do with the first code example which enforces return types.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download