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.

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

报告相同问题?