2015-06-01 58 views
0

我有一個父類和一小撮擴展該父類的子元素。PHP:爲什麼我無法更新父類的受保護屬性?

我想要做的是設置擴展到父項的子項的一些屬性。

下面是一個例子。

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使用空變量。

我在這裏錯過了什麼來正確地做到這一點?

+2

見文獻[延遲靜態綁定(http://php.net/manual/en/language.oop5.late-static-bindings.php) – Federkun

+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(); 
+0

關於整體靜態和合理建議風險的好處,但它不回答這個問題。 – GolezTrol

+0

感謝您澄清靜態屬性的用法。切換到使用'$ this'而不是完美工作。謝謝! –

相關問題