Search code examples
phpoopredbean

Dynamically set class array parameter, redbeanphp wrapper


I'm writing a wrapper for redbeanphp orm,

basically instead of using

$user = R::dispense('users');
$user->name = 'Zigi marx';
R::store($user);

I do like so

$user = new User();
$user->name = 'Zigi marx';
$user->save();

the way this is done is, I have a class called User that extends model and model runs Redbeanphp

the full code of my model can be found here http://textuploader.com/bxon

my problem is when I try to set a one to many relation, In redbean it is done like so

$user = R::dispense('users');
$user->name = 'Zigi marx';

$book = R::dispense('books');
$book->name = 'Lord of the rings II';
$user->ownBooks[] = $book;

and in my code

$user = new User();
$user->name = 'Zigi marx';
$book = new Book();
$book->name = 'Lord of the rings II';
$user->ownBooks[] = $book;

I get this error

Notice: Indirect modification of overloaded property Zigi\models\User::$ownBooks has no effect

The Answer: the __get function in model needed to be changed like so

public function & __get($name){
    $result =& $this->__bean->{$name};
    return $result;
}

Solution

  • Your __get method is returning the bean property by value, and so you cannot modify it afterward. To fix it, you need to return it by reference (see PHP manual), by adding a & to your method definition, like so:

    public function & __get($name){
        $result =& $this->__bean->$name;
        return $result;
    }