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 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误