我有一个父类和一些延伸父母的孩子。
我尝试做的是设置延伸到父级的子属性。
以下是一个例子。
class Activity {
protected static $activity;
protected static $data_sql;
protected static $field_prefix;
protected static $field_names;
//gets the data on a specific activity
public function get_data() {
$data = \DB::selectOne(self::$data_sql, [':id' => self::$activity['id']], \PDO::FETCH_ASSOC);
return $this->format_data($data);
}
}
class Post extends Activity {
protected static $activity;
protected static $data_sql = "SELECT * FROM post_activity_data WHERE activity_id = :id";
protected static $field_prefix = 'post_';
protected static $field_names = [
//set a handful of items
];
public function __construct($activity) {
self::$activity = $activity;
}
}
$data = new activity\Post($activity);
$new_data = $data->get_data();
在Post
中,它会扩展Activity
,但是当我运行get_data
时,它不会使用子类中设置的变量,而是尝试使用来自Activity
。
我在这里错过了什么来正确地做到这一点?
答案 0 :(得分:1)
这似乎不对。您创建了一个类的新实例:
$data = new activity\Post($activity);
但是在构造函数中,您设置了一个静态变量。这意味着它将由所有类共享。所以,如果以后你这样做:
$data = new activity\Post('');
您将删除之前所做的更改。
通过你的设置,我不认为使用静态变量是有意义的(有点像全局变量,因此应谨慎使用)。相反,您可以使用简单的成员变量:
class Activity {
protected $activity;
protected $data_sql;
protected $field_prefix;
protected $field_names;
//gets the data on a specific activity
public function get_data() {
$data = \DB::selectOne($this->$data_sql, [':id' => $this->$activity['id']], \PDO::FETCH_ASSOC);
return $this->format_data($data);
}
}
class Post extends Activity {
protected $activity;
protected $data_sql = "SELECT * FROM post_activity_data WHERE activity_id = :id";
protected $field_prefix = 'post_';
protected $field_names = [
//set a handful of items
];
public function __construct($activity) {
$this->$activity = $activity;
}
}
$data = new activity\Post($activity);
$new_data = $data->get_data();