Dynamic class names and namespaces

php.internals

Magnus Maatta

18 years ago
Hello, Using dynamic class names works fine without namespaces, but doesn't work at all with namespaces. Take this simple example: <?php namespace test; class Foo {} $class = "Foo"; $foo = new test::$class(); ?> Will produce the following message: Fatal error: Class 'test::test' not found in foo.php on line Y Now if Foo would have a static method and we want to use dynamic access for a static method, we get another error: <?php include 'foo.php'; $class = "Foo"; test::$class::test(); ?> Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ... All tested with current 5.3 /Magnus
-- Small things make base men proud. -- William Shakespeare, "Henry VI"

Stanislav Malyshev

18 years ago
> Using dynamic class names works fine without namespaces, but > doesn't work at all with namespaces. Take this simple example: > > <?php > namespace test; > class Foo {} > $class = "Foo"; > $foo = new test::$class(); > ?> > > Will produce the following message: > Fatal error: Class 'test::test' not found in foo.php on line Y
I don't think partially variable class name is supposed to work. It is interesting though how the engine managed to parse this at all...
-- Stanislav Malyshev, Zend Software Architect stas@zend.com http://www.zend.com/ (408)253-8829 MSN: stas@zend.com

Magnus Maatta

18 years ago
On Sunday 21 October 2007, Stanislav Malyshev wrote:
> > Using dynamic class names works fine without namespaces, but > > doesn't work at all with namespaces. Take this simple example: > > > > <?php > > namespace test; > > class Foo {} > > $class = "Foo"; > > $foo = new test::$class(); > > ?> > > > > Will produce the following message: > > Fatal error: Class 'test::test' not found in foo.php on line Y > > I don't think partially variable class name is supposed to work. It is > interesting though how the engine managed to parse this at all...
Ahh, I see, that's a bit disappointing. Any reason why it doesn't/shouldn't work ? /Magnus
-- One of the most striking differences between a cat and a lie is that a cat has only nine lives. -- Mark Twain, "Pudd'nhead Wilson's Calendar"

Stanislav Malyshev

18 years ago
> Ahh, I see, that's a bit disappointing. Any reason why it doesn't/shouldn't > work ?
Yes. Test::Foo is a class name, so you can't make part of it variable and part not, just as you couldn't write: $var = "bar"; $a = new foo$var(); and expect new instance of class "foobar". You'd have to compose the full name in variable and then use it.
-- Stanislav Malyshev, Zend Software Architect stas@zend.com http://www.zend.com/ (408)253-8829 MSN: stas@zend.com