Make namespaces backward compatible in PHP

So, I read about PHP namespaces, and I realized that in versions above 5.3, if you write

namespace MyNamespace 

You will get a parsing error.

Is there any way to avoid this, i.e. make namespaces backward compatible, so code isn't just crashing?

+4
source share
4 answers

Short answer: None.

Longer answer: (added to collect useful information from other deleted answers). The new syntax will lead to parsing errors in PHP, so you cannot use the client error handler to catch errors generated in versions <5.3. Theoretically, you could write a preprocessor for scanning and / or execute lex / parse in the source, and then write something back that would be compatible with PHP 5.2, but this creates more problems than it solves.

+4
source

Perhaps you could request the version of PHP used and call eval if it is tall enough. I don't know if this will work.

0
source

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

The shell will have to replace class names such as Foo\Bar\Baz with Foo_Bar_Baz . Currently, I'm not sure if there is anything that would make this impossible.

In any case, I do not think this is worth the effort. Update PHP 5.3.

Oh, that means the shell code must be compatible with PHP <5.3.

0
source

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

What I finally did to avoid parsing errors:

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

Source: https://habr.com/ru/post/1310905/


All Articles