开发者

Make namespaces backwards compatible in PHP

开发者 https://www.devze.com 2023-01-01 13:37 出处:网络
So I was reading about PHP namespaces, and I realized that in versions earlier than 5.3, if you write

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 开发者_如何学Pythonnamespaces backwards-compatible, so the code doesn't simply crash?


Short 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.


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.


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.


I know this is a very old question, but I needed to make a couple of instructions with namespaces backward compatible with a very old PHP installation (5.2).

What I finally did to avoid parse errors was:

if(version_compare(PHP_VERSION, '5.3.0') >= 0) {
    include("file_with_namespaces_code.php");
}
else{
    echo("put php 5.2 code here");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消