2012-02-24 2 views
1

나는 Id 추상 클래스를 확장하여 User 클래스를가집니다. 어떻게 든 Event이라는 또 다른 클래스를 도입하여 Id 클래스를 확장합니다. __construct() 메서드는 매우 유사하므로 Id 클래스에 생성자 코드를 넣으려고합니다. 나는 Id 클래스의 방법을 세우면부모 수준의 PHP 설정 값

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; 
     } 
    } 
} 

그러나, PHP는 $this->$property = $value; 날 경고 :

여기 내 __construct() 방법이다. Id 클래스에서 시작할 수 없도록 User 또는 Event 클래스에 private이라고 표시된 속성이 있습니다.

내가 원하는 그 변수를 private 유지하면서 내 코드를 재사용하는 것입니다

답변

0

일부 옵션 (I 그들에 액세스 할 부모 클래스를 제외하고 다른 싶지 않기 때문에!) :

  • 사용 protected 변수

  • Reflection을 사용하여 개인 변수를 속이고 설정할 수 있습니다.

  • 사용 특성 (5.4) 공통 __construct

  • 리팩토링을 조금 가져옵니다. 예 : 부모가 호출하는 하위 클래스에 setProperty이 있거나 __set 등을 구현하십시오.