라이브러리
[PHP] Yaf_View_Simple::__get - 할당된 변수 검색
Yaf_View_Simple::__get
Yaf_View_Simple은 PHP의 Yaf 프레임워크에서 제공하는 뷰 클래스입니다. 이 클래스는 뷰에서 변수에 접근할 때 사용하는 메소드 중 하나인 `__get` 메소드를 제공합니다.
# __get 메소드
`__get` 메소드는 객체의 속성을 읽을 때 호출되는 메소드입니다. 이 메소드는 객체의 속성이 존재하지 않아도 호출이 가능하며, 객체의 속성이 존재하지 않을 때는 `Notice: Undefined property` 오류가 발생합니다.
# 예제
#hostingforum.kr
php
// Yaf_View_Simple 인스턴스 생성
$view = new Yaf_View_Simple();
// 변수에 값을 할당
$view->name = 'John Doe';
// __get 메소드 호출
echo $view->name; // 출력: John Doe
// 존재하지 않는 속성에 접근할 때
echo $view->non_existent_property; // 출력: Notice: Undefined property
# __get 메소드 사용하기
`__get` 메소드는 뷰에서 변수에 접근할 때 사용할 수 있습니다. 예를 들어, 뷰에서 `$name` 변수에 접근할 때, `$view->name`으로 접근할 수 있습니다.
#hostingforum.kr
php
// Yaf_View_Simple 인스턴스 생성
$view = new Yaf_View_Simple();
// 변수에 값을 할당
$view->name = 'John Doe';
// 뷰에서 변수에 접근하기
echo $view->display(); // 출력: Hello, John Doe!
# __get 메소드 오버라이딩하기
`__get` 메소드는 오버라이딩할 수 있습니다. 예를 들어, 존재하지 않는 속성에 접근할 때 오류 메시지를 출력하는 코드를 작성할 수 있습니다.
#hostingforum.kr
php
// Yaf_View_Simple 인스턴스 생성
$view = new Yaf_View_Simple();
// __get 메소드 오버라이딩
class My_View_Simple extends Yaf_View_Simple {
public function __get($name) {
if (!property_exists($this, $name)) {
throw new Exception("Undefined property: $name");
}
return parent::__get($name);
}
}
// My_View_Simple 인스턴스 생성
$view = new My_View_Simple();
// 존재하지 않는 속성에 접근할 때 오류 메시지 출력
try {
echo $view->non_existent_property;
} catch (Exception $e) {
echo $e->getMessage(); // 출력: Undefined property: non_existent_property
}
# 결론
Yaf_View_Simple::__get 메소드는 뷰에서 변수에 접근할 때 사용할 수 있습니다. 또한, 오버라이딩하여 존재하지 않는 속성에 접근할 때 오류 메시지를 출력할 수 있습니다.
댓글목록
등록된 댓글이 없습니다.