tags:

views:

92

answers:

3

So I was reading about PHP namespaces, and I realized that in versions earlier than 5.3, if you write

namespace MyNamespace

you get a parse error.

Is there any way to avoid this i.e. make namespaces backwards-compatible, so the code doesn't simply crash?

+4  A: 

Long Answer: No.

Longer Answer: (added to capture useful information from other deleted answers). The new Syntax will cause parse errors in PHP, so you can't use a customer error handler to catch errors generated in versions < 5.3. In theory you could write a pre-processor the scans and/or does a lex/parse on the source and then write something back out that would be PHP 5.2 compatible, but that creates more problems than it solves.

Alan Storm
A: 

Perhaps you could query the version of PHP being used and call eval if it's high enough. I don't know if that will work though.

DeadMG
I don't think that would work. Namespaces are resolved at compile (well parse) time, whereas eval is resolved at run time...
ircmaxell
I thought that it could perform certain compile-time magicks, and that's why it can't be called from a variable function.
DeadMG
A: 

Actually, I think it's possible, but I don't believe it's worth it. The idea would be to create a custom default stream wrapper, which will parse PHP files according to the new grammar and make the appropriate changes to the syntax so that it will be valid PHP < 5.3.

The wrapper would have to replace class names such as Foo\Bar\Baz with Foo_Bar_Baz. Currently I'm not sure if there's something that would render this impossible.

Anyway, I don't believe it's worth the effort. Upgrade to PHP 5.3.

Oh, that means that the wrapper code should be compatible with PHP < 5.3.

Ionuț G. Stan