note 92851 deleted from function.eval by peehaa
| From: | peehaa@php.net | Date: | Mon, 09 Dec 2013 11:58:06 +0000 |
| Subject: | note 92851 deleted from function.eval by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197862@lists.php.net to get a copy of this message | ||
Note Submitter: Nico
----
eval and namespace
For those who wonder: since eval executes the code in another context than the current script, it is
possible to evaluate code that uses a particular namespace without changing the current one (and it
does not trigger an error if there is no namespace and the evaluated one is not at the top of the
script).
Exemple:
<?php
namespace Foo;
echo 'namespace 1: '.__NAMESPACE__."\n";
eval('namespace Bar;
class BarClass {}
echo \'namespace 2: \'.__NAMESPACE__."\n";');
echo 'namespace 1 again: '.__NAMESPACE__."\n";
?>
output:
namespace 1: Foo
namespace 2: Bar
namespace 1 again: Foo
And it will create the class Bar\BarClass.
Also, the eval code will not belong to the namespace of the code that do the eval:
<?php
namespace Foo;
echo 'namespace 1: '.__NAMESPACE__."\n";
eval('class BarClass {}
echo \'namespace 2: \'.__NAMESPACE__."\n";');
?>
output:
namespace 1: Foo
namespace 2: // global namespace