猿问

PHP Reflection——这是一个错误还是预期的行为?

我正在创建一个使用 ReflectionProperty 的类,但得到了奇怪的结果。


本质上,调用是返回一些完全不相关的数组$reflectionProperty->getType()->getName()的值。它在看似随机的条件下执行此操作。


见下文:


// this will be used as a type hinted property.

class DummyClass {

    public function __construct($arr) {}

}



// a class that sets its property values reflectively

class BaseClass {

    /** @var ReflectionProperty[] */

    private static $publicProps = [];


    /**

     * Gets public ReflectionProperties of the concrete class, and caches them

     * so we do not need to perform reflection again for this concrete class.

     *

     * @return ReflectionProperty[]

     * @throws ReflectionException

     */

    private function getPublicProps(){

        if (!static::$publicProps) {

            $concreteClass = get_class($this);

            static::$publicProps = (new ReflectionClass($concreteClass))

                ->getProperties(ReflectionProperty::IS_PUBLIC);

        }

        return static::$publicProps;

    }


请注意, 的值$propClassabc123def456——这是怎么发生的?

更多怪异

  • 将“abc123def456”的值更改为“12345678”即可。

  • 将“abc123def456”的值改为“123456789”,不起作用。

  • 省略 var_export(),它就会起作用。(不过,在其他情况下它仍然可能会损坏)。

我的直觉告诉我这是一个 PHP 错误,但我可能做错了什么,和/或这可能记录在某处。我想要一些澄清,因为目前我唯一可靠的解决方案是不缓存反射的 $publicProps。ReflectionClass->getProperties()这会导致每次创建新的时都会进行不必要的调用ConcreteClass,我想避免这种情况。


慕田峪7331174
浏览 91回答 1
1回答

猛跑小猪

事实证明这是 PHP 中的一个错误: https ://bugs.php.net/bug.php?id=79820此处的最小复制: https: //3v4l.org/kchfm7.4.9 中修复:https://www.php.net/ChangeLog-7.php#7.4.9
随时随地看视频慕课网APP
我要回答