Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel calling model after declaring function with colon

Tags:

php

laravel

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:

App\User::

What is the difference in this two approches?

like image 271
Leff Avatar asked May 26 '26 18:05

Leff


2 Answers

The first example you shared:

public function approve(): User

is simply a feature of PHP7 which allows you to use static type programming practices with PHP. Essentially this new function signature is telling you that this function needs to return a User type or it will throw a TypeError exception.

The second example you shared:

App\User::

is using what is called the Scope Resolution Operator(::) This operator allows you to call Class Level / Static Methods. In Laravel for example, that would be something like:

App\User::Find(1);

or

App\User::Where('id', 1);

and these differ from object level methods which would be called like so:

$user = new App\User();
$user->id = 1;
$user->save()

Notice the class instance uses the -> operator.

You can learn more about what I mentioned at the following links:

https://secure.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

https://laravel.com/docs/5.3/eloquent

Best of luck!

like image 116
Geoherna Avatar answered May 28 '26 07:05

Geoherna


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:
https://secure.php.net/manual/en/migration70.new-features.php

And treat yourself with Jeffrey's screencasts on PHP 7 new features:
https://laracasts.com/series/php7-up-and-running/episodes/3

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.

like image 26
sepehr Avatar answered May 28 '26 06:05

sepehr