Jump to content

Dynamic classname within a namespace - please help!


biz0r

Recommended Posts

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?

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();
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.