php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #55170 Hard-coded class creation doesn't follow same rules as dynamic (string-based)
Submitted: 2011-07-09 21:29 UTC Modified: 2015-06-18 18:01 UTC
From: phpbug at catchall dot drarok dot com Assigned:
Status: Duplicate Package: Scripting Engine problem
PHP Version: 5.3.6 OS: Mac OS X, possibly others
Private report: No CVE-ID: None
 [2011-07-09 21:29 UTC] phpbug at catchall dot drarok dot com
Description:
------------
Using PHP 5.3.6 on Mac OS X, I've found that hard-coding a class name into a 
script works fine, but attempting to create the same class using a string will not 
work, when relative namespaces are involved.

Test script:
---------------
<?php

namespace First\Second {
	class Test {
	}
}

namespace First {
	try {
		// This will work, as we're in First, so Second is relative.
		echo 'Creating hard-coded instance...', PHP_EOL;
		$instance = new Second\Test;
		echo 'Done.', PHP_EOL;
	} catch (Exception $e) {
		echo 'Failed!', PHP_EOL;
	}
	
	try {
		// This will *not* work, you have to use an absolute namespace like 'First\\Second\\Test'.
		echo 'Creating instance from string...', PHP_EOL;
		$class = 'Second\\Test';
		$instance = new $class;
		echo 'Done.', PHP_EOL;
	} catch (Exception $e) {
		echo 'Failed!', PHP_EOL;
	}
}

Expected result:
----------------
I'd expect the same results from either a string or a hard-coded class name.

Actual result:
--------------
PHP Fatal error:  Class 'Second\Test' not found

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-07-09 21:49 UTC] cataphract@php.net
-Status: Open +Status: Bogus
 [2011-07-09 21:49 UTC] cataphract@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.


 [2011-07-09 22:04 UTC] phpbug at catchall dot drarok dot com
Well, if this isn't a bug, then surely it's at least an undocumented "feature"? 
Should it be mentioned somewhere? Or was that response a knee-jerk reaction? 
Dynamic use of classes is pretty widely used, after all.
 [2015-06-18 18:01 UTC] cmb@php.net
-Status: Not a bug +Status: Duplicate
 [2015-06-18 18:01 UTC] cmb@php.net
Actually, this is a duplicate of bug #45197 and bug #46310, where the reason for this behavior is explained.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 13:01:31 2024 UTC