php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #54417 Add string casting support for class/interface names
Submitted: 2011-03-29 17:32 UTC Modified: 2015-01-04 19:26 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:1 (50.0%)
From: webseiten dot designer at googlemail dot com Assigned: ajf (profile)
Status: Closed Package: Class/Object related
PHP Version: Irrelevant OS: N/A
Private report: No CVE-ID: None
 [2011-03-29 17:32 UTC] webseiten dot designer at googlemail dot com
Description:
------------
Please add a way to get the fully qualified class or interface name without the need to create an object. While it is possible to declare a static variable in classes as a workaround, this will not work with interfaces, as you can't declare members inside them. A common trick I've seen is to use a constant:

namespace Foo\Bar;

interface A {
  const __NAME = __CLASS__;
}

factory(Bar\A::__NAME); // calls factory with '\Foo\Bar\A'

Though this won't work with inheritance. The magic __NAMESPACE__ constant is also no help when importing namespaces. I propose to use the __CLASS__ keyword to implement such a feature, as it is not allowed to have a class constant of this name:

namespace Foo\Bar {
  interface A {}
}

namespace Orange\Banana {
  use Foo\Bar;
  echo Bar\A::__CLASS__; // should print "Foo\Bar\A"
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-09-21 11:42 UTC] aigors at inbox dot lv
I find this idea very good in cases when you want to find all usages of the class 
over all project inside your IDE. When using class name as hardcoded string this 
isn't possible.

Also in PHP 5.3 possible workaround for this missing feature is to create method 
"static function __CLASS__() {return get_called_class();}" in all base classes 
which is extended by other classes. Sure it doesn't help for the interfaces.
 [2015-01-04 19:26 UTC] ajf@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: ajf
 [2015-01-04 19:26 UTC] ajf@php.net
Thank you for your bug report. This issue has already been fixed
in the latest released version of PHP, which you can download at 
http://www.php.net/downloads.php

PHP 5.5 added this (see RFC: https://wiki.php.net/rfc/class_name_scalars)

You can do ClassName::class to get its fully-qualified name.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Apr 14 18:01:30 2024 UTC