PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
class A
{
public $b;
public function __construct()
{
$this->b = new B();
}
}
class B
{
public $z = 10;
}
$a = new A();
$prop = 'b->z';
$a->$prop = 20;
echo $a->b->z;
Doesn't trigger an error,
Doesn't assign $a->b->z to 20,
Just leaves it as $a->b->z as 10.
If I want to do this I have to use reflection do I?
Using PHP 5.1.2
<?php
class A
{
public $b;
public function __construct()
{
$this->b = new B();
}
/**
* Set a public attribute to a value. Returns whether it could be set or not
*
* @param string $name
* @param string [,..$name]
* @param mixed $value
* @return bool
*/
public function set()
{
$args = func_get_args();
$value = array_pop($args);
$propertyChain = implode('->', $args);
$reflection = new ReflectionProperty($this, $args[0]);
if ($reflection->isPublic()) {
if (is_string($value)) {
$value = '\'' . addcslashes($value, '\'') . '\'';
}
eval('$this->' . $propertyChain . ' = ' . $value . ';');
return true;
}
return false;
}
}
class B
{
public $z = 10;
}
$a = new A();
$a->set('b', 'z', 20);
echo $a->b->z;
?>
seems to work
Last edited by Ollie Saunders on Tue Aug 01, 2006 7:22 pm, edited 1 time in total.