2012-02-24 85 views
1

我有一個User類擴展Id抽象類。不知何故,我會引入另一個類Event,擴展Id類。 __construct()方法非常相似,所以我想將構造函數代碼放在Id類中。php設置值在父級

這裏是我__construct()方法:

class Event extends Id 
{ 
    public function __construct($id, $object){ 
     $this->id = $id; 
     foreach($object as $property => $value) { 
      if (property_exists($this, $property)) $this->$property = $value; 
     } 
    } 
} 

class User extends Id 
{ 
    public function __construct($id, $object){ 
     $this->id = $id; 
     foreach($object as $property => $value) { 
      if (property_exists($this, $property)) $this->$property = $value; 
     } 
    } 
} 

但是,如果我把方法的Id類,PHP警告我在$this->$property = $value;。它說我在UserEvent類中有一些屬性private,所以它不能在Id類中啓動。

我想是重用我的代碼,同時保持這些變量private

回答

0

一些選項(因爲我不想讓其他的除了父類訪問它們!):

  • 使用protected變量

  • 您可以使用Reflection作弊並設置私有變量。

  • 使用特性(5.4)導入一個共同__construct

  • 重構了一下。例如在父母呼叫的子類中具有setProperty或實施__set