I have class
class User extends BaseModel{
public $id;
public $name;
}
class BaseModel{
function __construct($data=null){
if($data!=null)
//set $id and $name
}
}
I would like to set $id , $name and any other data that extends BaseModel by calling
$test = new User(array('id'=>1,'name'=>'user name'))
I tried to use
$this->__set($arrayKey,$arrayValue);
But i got error : Fatal error: Call to undefined method User::__set()
What am I doing wrong?
Thank you for any help.
Just loop through the data and assign each property:
The reason you got the error about
__set()not being defined is because you didn’t define it. Although__set()is a magic method, you do still have to define it’s behavior if you want to do something with it.This means if you try to “set” a class variable in a scope you’re not allowed to (like a private or protected variable), this function will run.