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?
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.