在另一个类中初始化一个类对象

时间:2014-06-26 14:48:28

标签: php class oop

我有一个包含以下内容的组类:

class Groups {   
protected $_db;
protected $member_id;
protected $group_id,$group_title;
public function __construct($db, $member_id) { 
    $this->_db = $db;
    $this->member_id = $member_id;
}
/** 
 * Set the group title
 *
 * @param str $group_id
 * 
 */
public function set_group_id($group_id) {
    $this->group_id = $group_id;    
}
/** 
 * Set the group id
 *
 * @param int $group_id
 * 
 */
public function get_group_id() {
    return $this->group_id; 
}
/** 
 * Set the group title
 *
 * @param str $group_id
 * 
 */
public function set_group_title($group_title) {
    $this->group_title = $group_title;  
}
/** 
 * get the group title
 *
 * @return int $group_id
 * 
 */
public function get_group_title() {
    return $this->group_title;
}
/** 
 * build existing group by id
 *
 * @param str $group_id
 * 
 */
public function fetch_group_by_id($group_id) {
    $sql = "SELECT * FROM `gps` WHERE `id` = ".sql_c($group_id)."
                    AND (`temp` != 'on' OR `temp` IS NULL)
                    AND (`backup` != 'on' OR `backup` IS NULL)";
    $result = @mysql_query($sql,$this->_db); check_sql(mysql_error(), $sql, 0);
    $list = mysql_fetch_array($result);
    $this->set_group_id($list['id']);
    //set all group properties from this group
    $this->set_group_title($list['title']);
   }
}

然后我创建了另一个名为group_value的类

我想在这个group_value类中初始化我的Group类,如下所示,但是当我尝试它时给了我意想不到的错误......

class Group_value extends Groups {
protected $_db;
protected $member_id;
protected $comment,
          $member_id,
          $group_id,
          $match,
          $match_id;    
function __construct($db, $member_id) {
    $this->_db = $db;
    $this->member_id = $member_id;
}

$groups = new Groups($db,$member_id); //HERE IT GIVES ME ERROR !! <<--
/** 
 * Set the comment
 *
 * @param str $comment
 * 
 */
public function set_comment($comment) {
    $this->comment = $comment;  
}                                                                     
}

要限制代码重复,我想在Group_value

中包含Groups类

2 个答案:

答案 0 :(得分:0)

$groups = new Groups($db,$member_id);移动到构造函数中:

function __construct($db, $member_id) {
    parent::__construct($db, $member_id);

    $this->groups = new Groups($db,$member_id);
}

并将其定义为受保护变量。

编辑:更改为调用父构造函数。

答案 1 :(得分:0)

使用parrent::protectedpublic属性或方法从Groups调用到Group_value,因为Group_value正在扩展Groups

同样在__construct Group_value你需要打电话给父母&#39; __construct就像这样parent::__construct();