2011-09-06 2 views
10

단순히 멤버 필드 컨테이너 인 불변 클래스를 생성해야합니다. 그 필드를 생성자에서 한번 인스턴스화하기를 원합니다 (값은 생성자에 매개 변수로 주어져야합니다). 난 필드를 공개하지만 불변으로하고 싶습니다. 각 필드 앞에 final 키워드를 사용하여 Java로 수행 할 수있었습니다. 그것은 PHP에서 어떻게 이루어 집니까?PHP : 불변의 public 멤버 필드

+3

이 PHP에서 할 수 없습니다. – Sjoerd

+0

필드를 공개해야하는 이유는 무엇입니까? – Pete171

+0

@ pete171 아마도 읽기 전용이므로 – fbstj

답변

16

의 dinamyc 수있는 경우 보호 또는 개인 :

class Example 
{ 
    private $value; 

    public function __construct() 
    { 
     $this->value = "test"; 
    } 

    public function __get($key) 
    { 
     if (property_exists($this, $key)) { 
      return $this->{$key}; 
     } else { 
      return null; // or throw an exception 
     } 
    } 

    public function __set($key, $value) 
    { 
     return; // or throw an exception 
    } 
} 

사용법 :

$example = new Example(); 
var_dump($example->value); 
$example->value = "invalid"; 
var_dump($example->value); 

출력 :

string(4) "test" 
string(4) "test" 
2

__set() 마법 방법을 사용하여 누군가가 속성을 직접 설정하려고 시도 할 때 예외를 throw 할 수 있습니다.

class ClassName { 
    public function __set($key, $value) { 
     throw new Exception('Can't modify property directly.'); 
    } 
} 

그러나 공개 여부에 관계없이 속성을 수정할 수는 없습니다.

+0

속성들은 private/어쨌든 보호되어있어 아무 것도 유용하지 않습니다. 반면에'__get()'은 우리가 원하는 것입니다. – Mchl

+3

__set()은 액세스 할 수없는 속성에 데이터를 쓸 때 실행됩니다. 공용으로 작동하지 않습니다. – jbrond

2

magic methods

그래서 당신은 더 잘 할 수 - 당신은 당신은 __set__get 마법 방법을 사용하고 해당 속성을 선언해야 필드

class ClassName { 
     private $fields = array(); 
     // use class : $cl = new ClassName(array('f'=>2,'field_4'=>5,''12)); 
     // echo $cl->field_4; echo $cl->f; 
     public function __construct($data= array()) 
     { 
      if (!is_array($data) || !count($data)) throw new Exception('Not enough args') 
      foreach ($data as $key=>$val) 
      { 
       if (is_numeric($key)) 
       $this->fields['field_'.$key] = $val; 
       else 
       $this->fields[$key] = $val; 
      }  
     } 
      /* in this case you can use this class like $cl = new ClassName(12,14,13,15,12); echo $cl->field_1; 
     public function __construct() 
    { 
      $ata = funcs_get_args(); 

      if (!count($data)) throw new Exception('Not enough args') 
      foreach ($data as $key=>$val) 
      { 
       if (is_numeric($key)) 
       $this->fields['field_'.$key] = $val; 
       else 
       $this->fields[$key] = $val; 
      }  
    } 
    */ 
     public function __get($var) { 
      if (isset($this->fields[$var])) 
       return $this->fields[$var]; 
      return false; 
      //or throw new Exception ('Undeclared property'); 
     } 
    } 
+4

'__set'은 공용 속성에 대해 호출되지 않습니다. – sanmai