`var_export()` combined with `enum` produces code unsuitable for inclusion in namespaces
Description
Following code: https://3v4l.org/MKPpJ
<?php
namespace A;
enum Foo { case BAR; }
$bar = var_export(Foo::BAR, true);
echo <<<PHP
<?php
namespace Generated\Code;
echo $bar;
PHP;
Resulted in this output:
<?php
namespace Generated\Code;
echo A\Foo::BAR;
But I expected this output instead:
<?php
namespace Generated\Code;
echo \A\Foo::BAR;
To be more specific:
<?php
namespace Generated\Code;
-echo A\Foo::BAR;
+echo \A\Foo::BAR;
This allows for generated PHP expressions (primary use-case of var_export()) to contain enums.
Ref: https://github.com/Ocramius/ProxyManager/issues/754#issuecomment-1073828730
PHP Version
8.1.4
Operating System
No response
Seems like this applies to both object and enum definitions - much older bug, exposed by the fact that property default values can now contain constants pointing to object references.
Thanks @iluuu1994!
Do I get it right that this issue was resolved? Just been bitten by it myself.
@AnrDaemon the merge commit is part of 8.2.0
Thanks. For pre-8.2 solution could be
<?=is_object($value) && version_compare(PHP_VERSION, '8.2.0', '<') ? "\\" : ''?><?=var_export($value, true)?>,
Thanks. For pre-8.2 solution could be
<?=is_object($value) && version_compare(PHP_VERSION, '8.2.0', '<') ? "\\" : ''?><?=var_export($value, true)?>,
~This is not valid in some cases, is_object is testing for any object, not just for enums. instanceof \UnitEnum should be used instead. https://3v4l.org/K68DW~
Edit: Only stdClass is an exception, so is_object($value) && $value::class !== 'stdClass'
What case you are thinking about is not valid?
@AnrDaemon Sorry, I didn't realize objects were also affected, so the problem is only with stdClass: https://3v4l.org/dJV8T
Yup, that seems the only special case. (As is the stdClass itself.) But in controlled environment (i.e. where you are sure you won't encounter stdClass ever), this workaround is applicable.