duanping1920 2014-10-27 05:28
浏览 225
已采纳

为什么ReflectionProperty-> setValue()方法没有设置属性,而是尝试设置字段? 如果我需要设置属性值该怎么办?

I written simple test that use Reflection to set property of some class instance:

namespace Rufanov\PHP\Tests
{
    class LaboratoryMouse
    {
        /** @var string */
        private $name;

        /**
         * @return string
         */
        public function getName()
        {
            return $this->name;
        }

        /**
         * @param string $name
         */
        public function setName($name)
        {
            $this->name = 'The awesome ' . $name;
        }
    }

    class ReflectionTests extends \PHPUnit_Framework_TestCase
    {
        public function testSetValue()
        {
            $reflectionClass = new \ReflectionClass('Rufanov\PHP\Tests\LaboratoryMouse');

            /** @var ReflectionTests $cat */
            $cat = $reflectionClass->newInstance();

            $nameProperty = $reflectionClass->getProperty('Name');
            $nameProperty->setValue($cat, 'Felix');

            $this->assertEquals('The awesome Felix', $cat->getName());
        }
    }
}

It fails...

I have experience with other object-oriented programming languages, that also have reflection. And so i've expected from PHP that it will set property value. If you want from OOP language to set property value for you, it should find object property and set it's value by calling setter method, right?

But PHP does something different here - it tries to set FIELD value, that is not exists as expected. Why??? How can i set value of some property in PHP if i only know it's name?

  • 写回答

1条回答 默认 最新

  • doushi4864 2014-10-27 07:18
    关注

    The property is defined by the private $name;, not by the two methods that indirectly set and get that value. The property class simply doesn't know that you consider these two functions the getters and setters for $name. It doesn't care either, it just provides access to the class' and/or object's properties.

    What you can do, if you follow a consistent naming schema, is to use this syntax:

    $cat->{'set' . $property}('Fritz');
    

    (I think that works. If not, you might have to call_user_method().)

    A completely different approach is to implement __get() and __set() for your class. Using these, you can intercept property access, which makes the separate getters and setters obsolete.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀