라이브러리
[PHP] ReflectionMethod::setAccessible - 메서드 접근성 설정
ReflectionMethod::setAccessible
PHP의 ReflectionMethod::setAccessible 메소드는 private 또는 protected 메소드를 public 메소드로 만들어서 접근할 수 있도록 합니다. 이 메소드는 ReflectionClass의 인스턴스를 통해 호출할 수 있습니다.
사용법
ReflectionMethod::setAccessible 메소드는 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
php
$reflectionClass = new ReflectionClass('클래스명');
$method = $reflectionClass->getMethod('메소드명');
$method->setAccessible(true);
예제
다음 예제는 ReflectionMethod::setAccessible 메소드를 사용하여 private 메소드를 호출하는 방법을 보여줍니다.
#hostingforum.kr
php
class MyClass {
private function myPrivateMethod() {
echo "Private method called
";
}
}
$reflectionClass = new ReflectionClass('MyClass');
$method = $reflectionClass->getMethod('myPrivateMethod');
$method->setAccessible(true);
$method->invoke(new MyClass()); // Private method called
예제 2 - private 속성 접근
ReflectionMethod::setAccessible 메소드는 private 속성에 접근할 수 있도록 해줍니다.
#hostingforum.kr
php
class MyClass {
private $myPrivateProperty;
public function __construct() {
$this->myPrivateProperty = 'Private property value';
}
public function getMyPrivateProperty() {
return $this->myPrivateProperty;
}
}
$reflectionClass = new ReflectionClass('MyClass');
$property = $reflectionClass->getProperty('myPrivateProperty');
$property->setAccessible(true);
echo $property->getValue(new MyClass()); // Private property value
예제 3 - private 메소드와 속성 접근
ReflectionMethod::setAccessible 메소드는 private 메소드와 속성에 접근할 수 있도록 해줍니다.
#hostingforum.kr
php
class MyClass {
private $myPrivateProperty;
public function __construct() {
$this->myPrivateProperty = 'Private property value';
}
private function myPrivateMethod() {
echo "Private method called
";
return $this->myPrivateProperty;
}
}
$reflectionClass = new ReflectionClass('MyClass');
$method = $reflectionClass->getMethod('myPrivateMethod');
$method->setAccessible(true);
$property = $reflectionClass->getProperty('myPrivateProperty');
$property->setAccessible(true);
echo $method->invoke(new MyClass()) . "
"; // Private property value
echo $property->getValue(new MyClass()) . "
"; // Private property value
주의사항
ReflectionMethod::setAccessible 메소드는 private 메소드와 속성을 public 메소드와 속성으로 만들기 때문에 주의해서 사용해야 합니다. 이 메소드를 사용할 때는 반드시 필요한 경우에만 사용하고, 사용하지 않아야 하는 경우에는 사용하지 않도록 하세요.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.