Background
[wp_ad_camp_1]
There are times you need to refer to a class by a string representing its fully qualified class name. For example in Laravel 4.2, you may specify a route to a controller by hard-coding the fully qualified class name. However, this is not a good practice as classes may be moved to different namespaces overtime specially during the development stage. Since I am from a Java background, I tend to reuse some terms and terminologies in other platform. In Java speak, a class’ canonical name is simply its fully qualified class name. So, this article simply demonstrates how to retrieve a class’ fully qualified name.
Software Requirements
- Windows 7 Professional SP1
- PHP 5.6.3 / Zend Engine v2.6.0
- NetBeans IDE 8.0.1
Canonical Name equals Fully Qualified Class Name
There are two scenarios where you can get a class’ canonical name – via the class itself and an instance of that class.
Get canonical name statically
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | namespace com\turreta\controller; class LoginController extends ApiGuardController implements RestController { public static function canonicalName() { return static::class; } public function loginUser() {/* Logic here */} } // Usage: use com\turreta\controller; LoginController.canonicalName(); // Using with Laravel routes Route::get('/login', LoginController::canonicalName() . '@loginUser'); |
Get canonical name via instance of a class
1 2 3 4 5 6 | namespace com\turreta\dto; class SomeDTO { } // Usage use com\turreta\dto\SomeDTO; get_class(new SomeDTO()); |
[wp_ad_camp_3]