biz0r Posted September 21, 2010 Share Posted September 21, 2010 I am stumped as to why this simple code will not work...anyone care to enlighten me? <? namespace test; class testClass { function go() { echo "hello world"; } } $x='testClass'; $t = new $x(); $t->go(); ?> Running that code gives me this error: Fatal error: Class 'testClass' not found in test.php on line 11 If I remove the namespace declaration it works fine...anyone? Link to comment https://forums.phpfreaks.com/topic/213954-dynamic-classname-within-a-namespace-please-help/ Share on other sites More sharing options...
biz0r Posted September 21, 2010 Author Share Posted September 21, 2010 Nevermind guys...I found out for variable variables you need to use the full path when referencing a class. The following fixed it for those interested: <?php namespace test; class testClass { function go() { echo "hello world"; } } $x = __NAMESPACE__.'\\testClass'; $t = new $x(); $t->go(); ?> Link to comment https://forums.phpfreaks.com/topic/213954-dynamic-classname-within-a-namespace-please-help/#findComment-1113505 Share on other sites More sharing options...
vungee Posted September 21, 2010 Share Posted September 21, 2010 You can declare the namespace using backslashes as well <? namespace test; class testClass { function go() { echo "hello world"; } } $x='\test\testClass'; $t = new $x(); $t->go(); ?> Link to comment https://forums.phpfreaks.com/topic/213954-dynamic-classname-within-a-namespace-please-help/#findComment-1113506 Share on other sites More sharing options...
biz0r Posted September 21, 2010 Author Share Posted September 21, 2010 yep...that is basically the same thing . Thanks for the reply. Link to comment https://forums.phpfreaks.com/topic/213954-dynamic-classname-within-a-namespace-please-help/#findComment-1113514 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.