Leonardo Leonardo - 5 months ago 8
PHP Question

What does <namespace>::class mean?

In a CakePHP Plugin documentation there is the following code line:

$validator->provider('upload', \Josegonzalez\Upload\Validation\DefaultValidation::class);


\Josegonzalez\Upload\Validation\DefaultValidation
is the namespace, but I didn't understand the
::class
. Could someone explain it? I didn't find anything in PHP documentation.

Answer

the class constant simply returns the full name of the class (with namespace) as a string. So instead of passing as string to some method that requires it, you pass it the PHP way. It just looks nice, for example:

$validator->provider('upload',\Josegonzalez\Upload\Validation\DefaultValidation::class);

AND

$validator->provider('upload', '\Josegonzalez\Upload\Validation\DefaultValidation');

Both Are Same

And another advantage of this is that, if you need full class name several times in a single file.. say onto multiple method calls as a parameter. You can simply use it on the top & then only the classname will return the full name with namespace. like this:

use \Josegonzalez\Upload\Validation\DefaultValidation;

$validator->provider('upload', DefaultValidation::class);

//you can use it on other places as well, if required.
$someOtherClass->someOtherMethod(DefaultValidation::class);

So, in short, it reduces the number of characters you need to type, and makes your code look cleaner.

Comments