Defining items in the constructor
I have this little piece of code, I want to be able to define each element of the array as a new data element.
class Core_User
{
protected $data_members = array(
'id' => '%d',
'email' => '"%s"',
'password' => '"%s"',
'title' => '"%s"',
'first_name' => '"%s"',
'last_name' => '"%s"',
'time_added' => '%d' ,
'time_modified' => '%d' ,
);
function __construct($id = 0, $data = NULL)
{
foreach($this->data_members as $member){
//protected new data member
}
}
+2
a source to share
3 answers
What you want to achieve is possible, however you will not be able to create new properties protected
(as this is only possible for predefined members).
function __construct($id = 0, $data = NULL)
{
foreach($this->$data_memebers as $name => $value ){
$this->$name = $value;
}
}
Note the use of $
before name
in $this->$name
: this forces PHP to use the current value of the variable $name
as a property.
0
a source to share
- Always use $ this when you want to access the members of an object (this should be $ this-> data_members in the constructor).
-
You can try defining the magic methods __get and __set (I'm not sure if they can be protected though).
protected function __get($name){ if (array_key_exists($name,$this->data_memebers)) { return $this->data_memebers[$name]; } throw new Exception("key $name doesn't not exist"); } protected function __set($name,$value){ if (array_key_exists($name,$this->data_memebers)) { $this->data_memebers[$name] = $value; } throw new Exception("key $name doesn't not exist"); }
0
a source to share