php.net |  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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: marcus at synchromedia dot co dot uk
New email:
PHP Version: OS:

 

 [2016-04-05 18:05 UTC] marcus at synchromedia dot co dot uk
Description:
------------
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:
---------------
<?php
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


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-04-07 06:21 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2016-04-07 06:21 UTC] nikic@php.net
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-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 18:01:29 2024 UTC