|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71970 Dynamic class names don't work with aliases
Submitted: 2016-04-05 18:05 UTC Modified: 2016-04-07 06:21 UTC
From: marcus at synchromedia dot co dot uk Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.6.20 OS:
Private report: No CVE-ID: None
 [2016-04-05 18:05 UTC] marcus at synchromedia dot co dot uk
In simple cases, creating a class instance where the name of the class is in a string, it generally works as per the docs:

$a = 'myclass';
$b = new $a; //works

But if the class name is from an aliased import, it fails.

use Some\Project\myclass;
$a = 'myclass';
$b = new $a; //fails

Adding a __NAMESPACE__ prefix (as per bug #53904) doesn't work because it uses the current namespace, not the aliased one.

It's impossible to work around this with reflection because the class may not yet be loaded, so there seems to be no way of getting the namespace that an aliased name belongs to.

I think this is a bug (or feature) in the order of resolving the class name before creating it. PHP resolves the class name but does not apply alias mappings to it before using it.

Test script:
namespace my\project;

require 'vendor/autoload.php';

use League\OAuth2\Client\Provider\Google;
use Stevenmaguire\OAuth2\Client\Provider\Microsoft;

$provider = 'Google';
$nprovider = __NAMESPACE__ . $provider;

$a = new Google; //Succeeds
$a = new $provider; //Fails
$a = new $nprovider; //Fails - wrong namespace


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2016-04-07 06:21 UTC]
-Status: Open +Status: Not a bug
 [2016-04-07 06:21 UTC]
String class names always expect a fully qualified name. If you want to get the fully qualified name of an aliased, use myclass::class notation.
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Mon Dec 11 00:01:26 2023 UTC