Reputation: 1502
In one of my projects we are having a function which validates objects like:
if( true == valObj( $someObj, 'SomeClass' ) ) {
//Do some work;
}
While using this I thought this can be written like:
if( true == valObj( $someObj, SomeClass::class ) ) {
//Do some work;
}
Now I just want to know which approach is better and why? Or are they same?
Upvotes: 0
Views: 676
Reputation: 1656
The ::class
notation is generally better as it allows for easier usage finding and thereby refactoring: If you use an IDE like PHPStorm you can easily rename a class, and it will find and update all usages of OldClassName::class
to NewClassname::class
. This is not the case for the hardcoded string variant.
If you use namespaces using this notation can also result in less inline characters.
If you are running a PHP version that supports this notation, use it :)
Upvotes: 2
Reputation: 7896
from php.net
The special ::class
constant are available as of PHP 5.5.0, and allows for fully qualified class name resolution at compile, this is useful for namespaced classes.
<?php
namespace foo {
class bar {
}
echo bar::class; // foo\bar
}
?>
This is also a magic constant. have a look at http://php.net/manual/en/language.constants.predefined.php
Upvotes: 0
Reputation: 482
SomeClass::class
returns the full namespace including the class name.
Whilst if you use the string notation you have to add the namepace (if any) yourself.
Edit:
It doesn't matter which notation you choose, although I personally prefer the string notation as it shows you directly what namespace the class is in while scrolling through code.
Upvotes: 1