Define data members within constructor
-
02-10-2019 - |
Pergunta
I have got this little snippet of code, I want to be able to define each array element as a new data member.
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
}
}
Solução
//protected new data member
You won't be able to create a non-public property at runtime. If protected is paramount, you can declare a protected array or object and insert key/values into it in the constructor
Outras dicas
- Always use $this when you want to access object's members (it should be $this->data_members in constructor).
You can try defining magic methods __get & __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"); }
What you want to achieve is possible, however you won't be able to make the 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 the $
before name
in $this->$name
: This makes PHP use the current value of the $name
variable as property.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow