php-src icon indicating copy to clipboard operation
php-src copied to clipboard

`var_export()` combined with `enum` produces code unsuitable for inclusion in namespaces

Open Ocramius opened this issue 4 years ago • 9 comments

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

Ocramius avatar Mar 21 '22 12:03 Ocramius

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.

Ocramius avatar Mar 21 '22 12:03 Ocramius

Thanks @iluuu1994!

Ocramius avatar Apr 23 '22 09:04 Ocramius

Do I get it right that this issue was resolved? Just been bitten by it myself.

AnrDaemon avatar Dec 07 '22 12:12 AnrDaemon

@AnrDaemon the merge commit is part of 8.2.0

Ocramius avatar Dec 07 '22 12:12 Ocramius

Thanks. For pre-8.2 solution could be

<?=is_object($value) && version_compare(PHP_VERSION, '8.2.0', '<') ? "\\" : ''?><?=var_export($value, true)?>,

AnrDaemon avatar Dec 07 '22 14:12 AnrDaemon

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'

KapitanOczywisty avatar Dec 07 '22 17:12 KapitanOczywisty

What case you are thinking about is not valid?

AnrDaemon avatar Dec 08 '22 07:12 AnrDaemon

@AnrDaemon Sorry, I didn't realize objects were also affected, so the problem is only with stdClass: https://3v4l.org/dJV8T

KapitanOczywisty avatar Dec 08 '22 12:12 KapitanOczywisty

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.

AnrDaemon avatar Dec 09 '22 10:12 AnrDaemon