written: Sep 30 2005
last modified: Oct 11 2005
protected 멤버
protected 멤버는 해당 클래스 멤버뿐만 아니라 클래스를 상속받은 하위클래스에서도 상위클래스의 protected 멤버에 접근할 수 있습니다.
protected로 선언된 멤버의 경우에 C++이냐 자바냐에 따라 그 의미가 약간씩 다르기도 하고 추가되는 개념도 있습니다. 가장 큰 차이점은 C++에서는 바로 아래에 있는 하위 클래스에서만 접근할 수 있는 반면에 자바에서는 패키지라는 개념이 도입되어 패키지 안에 있는 어떤 클래스도 접근할 수 있게 해 줍니다. PHP5에서는 해당 클래스로부터 상속된 모든 하위클래스에서 접근할 수 있습니다.
해당 클래스에서는 protected 선언하나 private 멤버로 선언하나 그 동작이 동일합니다. 또한 다른 클래스나 전역영역에서 접근할 수 없다는 것도 동일합니다. 해당 클래스로부터 상속받은 하위클래스에서만 차이가 납니다. 상위클래스에서 private로 선언된 멤버는 접근할 수 없으나 protected로 선언된 멤버는 하위클래스에 상속되어 자유로이 접근할 수 있습니다.
[code php;gutter:false]
<?php
class my_class {
protected $protected1 = "my_class::protected1!\n";
protected $protected2 = "my_class::protected2!\n";
protected function my_protected1() {
return "my_class::my_protected1()!\n";
}
protected function my_protected2() {
return "my_class::my_protected2()!\n";
}
function foo() {
print "my_class::foo() " . $this->protected1;
print "my_class::foo() " . $this->protected2;
print "my_class::foo() " . $this->my_protected1();
print "my_class::foo() " . $this->my_protected2();
}
}
class my_class2 extends my_class {
protected $protected1 = "my_class2::protected1!\n";
protected function my_protected1() {
return "my_class2::my_protected1()!\n";
}
function foo2() {
print "my_class::foo2() " . $this->protected1;
print "my_class::foo2() " . $this->protected2;
print "my_class::foo2() " . $this->my_protected1();
print "my_class::foo2() " . $this->my_protected2();
}
}
$obj2 = new my_class2;
/**
* Will output
* "my_class::foo2() my_class2::protected1!"
* "my_class::foo2() my_class::protected2!"
* "my_class::foo2() my_class2::my_protected1()!"
* "my_class::foo2() my_class::my_protected2()!"
*/
$obj2->foo2();
?>
[/code]
< protected로 지정된 멤버의 동작 >
'phpclass > 객체모델' 카테고리의 다른 글
{PHP5 객체모델}06.범위지정연산자(::) (0) | 2005.10.11 |
---|---|
{PHP5 객체모델}05.Public 멤버 (0) | 2005.10.11 |
{PHP5 객체모델}03.Private 멤버 (0) | 2005.10.11 |
{PHP5 객체모델}02.PPP 접근제한자 (0) | 2005.10.11 |
{PHP5 객체모델}01.가시범위 (0) | 2005.10.11 |