Enhanced __CLASS__ constant
| From: | David Grudl | Date: | Wed, 21 Jan 2009 21:05:14 +0000 |
| Subject: | Enhanced __CLASS__ constant | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-42756@lists.php.net to get a copy of this message | ||
Especially in namespaced code it should be very useful to have "something" returning fully qualified name as string. It can be operator, but I think introducing new keyword is bad way, or it can be realized using well known magic constant in new context:
Example:
function factory($class)
{
return new $class;
}
$obj = factory('MyClass'); // returns object MyClass
$obj = factory(MyClass::__CLASS__); // returns again object MyClass, code is little bit more selfexplaining
But big advantages are in namespaced code (especially when you refactor a code):
namespace Foo;
use Other\Bar;
$obj = factory('MyClass'); // ERROR - returns object \MyClass, must be refactored to:
$obj = factory(__NAMESPACE__ . '\\MyClass'); // very very ugly! :-(
$obj = factory('Other\Bar'); // use statement must be duplicated here :-(
// with magic contant:
$obj = factory(MyClass::__CLASS__); // returns object Foo\MyClass, very understandable :-)
$obj = factory(Bar::__CLASS__); // returns object Other\Bar, as use statement declares :-)
David Grudl