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?