PHP OOP에서 정적 메소드와 $this
정적 메소드 내부에서는 $this를 사용할 수 없습니다.
이는 정적 메소드가 객체 컨텍스트 없이,
단순히 클래스 이름을 참조하여 호출될 수 있기 때문입니다.
일반 메소드에서는 정적 속성과 메소드, 그리고 일반 속성과 메소드 모두에 접근할 수 있습니다.
예제를 통해 살펴보겠습니다. 일반 메소드 예제:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public function method()
{
echo self::$staticProperty; // 'static' 출력
echo $this->usualProperty; // 'usual' 출력
}
}
$test = new Test;
$test->method();
?>
정적 메소드 예제:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public static function method()
{
echo self::$staticProperty; // 'static' 출력
echo $this->usualProperty; // 오류 발생
}
}
$test = new Test;
$test::method();
?>