단순히 멤버 필드 컨테이너 인 불변 클래스를 생성해야합니다. 그 필드를 생성자에서 한번 인스턴스화하기를 원합니다 (값은 생성자에 매개 변수로 주어져야합니다). 난 필드를 공개하지만 불변으로하고 싶습니다. 각 필드 앞에 final
키워드를 사용하여 Java로 수행 할 수있었습니다. 그것은 PHP에서 어떻게 이루어 집니까?PHP : 불변의 public 멤버 필드
10
A
답변
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.');
}
}
그러나 공개 여부에 관계없이 속성을 수정할 수는 없습니다.
2
그래서 당신은 더 잘 할 수 - 당신은 당신은 __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
관련 문제
- 1. Public 속성 및 개인 멤버 C#
- 2. C++ : 클래스 외부에서 public 멤버 함수에 액세스
- 3. 불변의 객체는
- 4. Type.GetFields() - "public const"필드 만 반환하기
- 5. .NET 불변의 객체
- 6. Doctrine 2의 불변의 콜렉션?
- 7. Java 클래스 public 멤버 변수를 Ant에서 액세스하여 빌드 작업에 사용하십시오.
- 8. 액션 -methods와 PHP 프레임 워크의 public 메소드
- 9. C에서 특정 유형의 멤버 필드 찾기
- 10. 이것은 불변의 우수 사례입니까? 가정하자
- 11. 매핑 불변의 속성 여기
- 12. 파이썬 불변의 유형을 변경
- 13. 불변의 닷 넷 문자열
- 14. 불변의 사전 오버 헤드?
- 15. 불변의 클래스는 메모리를 저장합니까?
- 16. 불변의 참조 란 무엇입니까?
- 17. 멤버 변수에 PHP 중괄호 구문
- 18. PHP 동적 멤버 변수 나열
- 19. 불변의 오브젝트로 사용되는 팩토리와 같은 (java) 메소드
- 20. public static synchronized와 public static의 차이점은 무엇입니까?
- 21. 클래스 멤버
- 22. PHP 고유 텍스트 필드?
- 23. 양식 필드 안정성 PHP
- 24. PHP 200+ 양식 필드
- 25. Public LinkedList
- 26. 불변의 크롬 sqlite 반환 객체
- 27. 파이썬, 서브 클래스 불변의 유형
- 28. PocketPC - VT_DATE 불변의 VT_BSTR로 변환
- 29. 불변의 문자열 대 std :: 문자열
- 30. 함수 호출에서 파이썬 불변의 타입
이 PHP에서 할 수 없습니다. – Sjoerd
필드를 공개해야하는 이유는 무엇입니까? – Pete171
@ pete171 아마도 읽기 전용이므로 – fbstj