2010-04-29 52 views
2

我已经得到了这个小小的代码片段,我希望能够将每个数组元素定义为新的数据成员。在构造函数中定义数据成员

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 
     } 

    } 

回答

0

//保护的新的数据成员

您将无法在运行时创建一个非公共财产。如果保护的是最重要的,你可以声明一个受保护的数组或对象,并在构造函数中插入键/值到它

0

你想达到什么是可能的,但是你将无法使新属性protected(因为这是唯一可能的预定义的成员)。

function __construct($id = 0, $data = NULL) 
{ 
    foreach($this->$data_memebers as $name => $value){ 
     $this->$name = $value; 
    } 
} 

注意使用$之前name$this->$name:这使得PHP使用$name变量属性的当前值。

0
  1. 总是使用$这个时候你要访问对象的成员(应该在$这个 - > data_members构造函数)。 (
  2. 你可以尝试定义魔法方法__get & __set(我不确定它们是否可以被保护)。 :

    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"); 
    } 
    
相关问题