macondo_buendia
macondo_buendia

Reputation: 21

What is the SomeClass::class.'@someMethod' syntax pattern in PHP?

I have never seen this before in PHP and have zero clue how to search for this. I was pulling up some Java examples, and that really doesn't help.

Specifically, I saw this in Laravel's Spark in the scriptVariables() method within the main Spark object. I have an idea of what this is doing, but what's the difference between this and simply writing: SomeClass::someMethod()?

And please show me the correct place in the manual, if that exists. Just point me in the right direction.

Upvotes: 0

Views: 278

Answers (1)

Luceos
Luceos

Reputation: 6720

The actual difference between ::class and a static call ::someMethod() is that ::class on any object will return the FQCN of a class (fully qualified class name). Take the following example class:

namespace Macondo\Buendia\Admin;

class User {}

Running the following;

echo Macondo\Buendia\Admin\User::class;

or

use Macondo\Buendia\Admin\User;
echo User::class;

Will both return:

Macondo\Buendia\Admin\User

This makes it pretty easier, for instance in route declarations of Laravel to create a decent, persistent way of defining the controller actions:

Route::get('/', App\Http\Controllers\HomeController::class . '@home');
Route::get('/dashboard', App\Http\Controllers\HomeController::class . '@dashboard');

https://laravel.com/docs/5.6/controllers#controllers-and-namespaces


To clarify, the SomeController::class . '@someMethod' is not a static call. Laravel will resolve the specific controller and method using "the Container" (also called inversion of control/ioc).

Upvotes: 3

Related Questions