$this ->shape
역할
$this 는 instance(개별 객체) - 현재 인스턴스의 함수나 변수를 가리킬 때 사용한다.
만약, $this를 빼먹으면 멤버 변수(함수)가 아니라 그 위치에서의 지역변수(함수)로 처리된다.
즉 $this는 개별 객체 - 인스턴스의 함수나 변수를 가리킨다.
"$this" 의 의미는 현재 자신을 나타내는 표현이고,
"->" 의 의미는 객체 내의 속성이나 메소드를 가리킬 때 사용한다.
결론적으로 "$this->shape" 은 현재 객체 내의 shape라는 속성을 가리킨다.
예제 코드
class printer {
function print_hello(){
echo "hello world!";
}
function __construct(){
$this->print_hello(); // "hello world!"
self->print_hello(); // "hello world!"
}
}
$self 는 static- 명령이 실행되는 위치의 클래스 자체에 속하는 함수나 변수를 가리킬 때 사용한다.
class self_this{
private $this_var = "인스턴스 변수";
private static $self_var = "정적 변수";
function test(){
echo "이것은 인스턴스 변수입니다. : " . $this->this_var;
echo "이것은 정적 변수입니다. : " . self::$self_var;
}
}
-> 는 객체의 속성에 접근하는 방법이다.
예를 들어, new 키워드를 통해 생성한 user 클래스에 대입한 $object의 name 속성에 접근하기 위해서, 또는 객체의 메소드인 printUser()에 접근하기 위해서는 아래의 코드와 같이 접근해야 한다.
$object -> name;
$object - > printUser();
상속된 클래스를 만들면 확인해볼 수 있다.
class printer {
function print_hello(){
echo "hello world!";
}
function __construct(){
$this->print_hello(); // "hi"
echo ', ';
self::print_hello(); // "hello world!"
}
}
class echo_printer extends printer {
funciton print_hello(){
echo "hi";
}
}
$obj = new echo_printer();
obj)를 가리키고,
self 는 명령이 실행되는 위치 __contstruct 의 클래스 자체를 가리키기 때문이다.
대부분의 경우에는 $this 를 사용하자.
현재 클래스를 가리켜야만 하는 경우 (static 등) 에는 self를 사용한다.