PHP의 반사 반사 메커니즘 소개

不言
풀어 주다: 2023-04-02 15:06:01
원래의
1227명이 탐색했습니다.

이 글은 주로 PHP의 Reflection 반사 메커니즘에 대한 소개입니다. 이제 특정 참조 값이 있으므로 필요한 친구가 참조할 수 있습니다.
# 🎜🎜#

PHP5에는 반사라는 새로운 기능이 추가되었습니다. 이 기능을 사용하면 프로그래머는

reverse-engineer [리버스 엔지니어링] 클래스, 인터페이스, 함수, 메서드 및 확장 [확장 라이브러리 지원]을 수행할 수 있습니다.

PHP 코드를 통해 객체의 모든 정보를 얻고 상호작용할 수 있습니다.

다음 Person 클래스를 가정합니다.

 1 class Person { 
 2     /** 
 3      * For the sake of demonstration, we"re setting this private 
 4      */ 
 5     private $_allowDynamicAttributes = false; 
 6      
 7     /** 
 8      * type=primary_autoincrement 
 9      */
 10     protected $id = 0;
 11     
 12     /**
 13      * type=varchar length=255 null
 14      */
 15     protected $name;
 16     
 17     /**
 18      * type=text null19      */
 20     protected $biography;
 21     public function getId() {
 22         return $this->id;
 23     }
 24     public function setId($v) {
 25         $this->id = $v;
 26     }
 27     public function getName() {
 28         return $this->name;
 29     }
 30     public function setName($v) {
 31         $this->name = $v;
 32     }
 33     public function getBiography() {
 34         return $this->biography;
 35     }
 36     public function setBiography($v) {
 37         $this->biography = $v;
 38     }
 39 }
로그인 후 복사
ReflectionClass를 통해 Person 클래스의 다음 정보를 얻을 수 있습니다.

    # ㅋㅋㅋ 🎜# # 🎜🎜#
  • 정적 속성 정적 속성

  • Namespace Namespace

  • Person 클래스 여부 final 또는 abstract입니다.

  • 클래스 이름 "Person"을 ReflectionClass에 전달하세요.

    1 $class = new ReflectionClass('Person');
    로그인 후 복사
    * 속성 가져오기(Properties): # 🎜🎜 #
    1 $properties = $class->getProperties();2 foreach($properties as $property) {
    3     echo $property->getName()."\n";4 }
    5 // 输出:6 // _allowDynamicAttributes7 // id8 // name9 // biography
    로그인 후 복사
  • 기본적으로 ReflectionClass는 개인 속성과 보호 속성을 포함한 모든 속성을 가져옵니다. 비공개 속성만 가져오려면 추가 매개변수를 전달해야 합니다:
  • 1 $private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
    로그인 후 복사

    사용 가능한 매개변수 목록:

  • ReflectionProperty:: IS_STATIC#🎜 🎜#

반사 속성::IS_PUBLIC

반사 속성::IS_PROTECTED

# 🎜🎜## 🎜🎜#

ReflectionProperty::IS_PRIVATE

  • 공용 속성과 개인 속성을 모두 가져오려면 다음과 같이 작성하세요. ReflectionProperty::IS_PUBLIC | ReflectionProperty: :IS_PROTECTED

    속성 이름은 $property->getName()을 통해 얻을 수 있으며, 속성에 작성된 설명은 getDocComment를 통해 얻을 수 있습니다.
 1 foreach($properties as $property) {
 2     if($property->isProtected()) { 
 3         $docblock = $property->getDocComment(); 
 4         preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches); 
 5         echo $matches[1]."\n"; 
 6     } 
 7 } 
 8 // Output: 
 9 // primary_autoincrement
 10 // varchar
 11 // text
로그인 후 복사
  • 좀 놀랍습니다. 댓글을 받을 수도 있습니다.

    * 메소드 가져오기(methods): getMethods()를 통해 클래스의 모든 메소드를 가져옵니다. 반환되는 것은 ReflectionMethod 개체의 배열입니다.
  • 더 이상의 시연은 없습니다.

    * 마지막으로 ReflectionMethod를 통해 클래스의 메서드를 호출합니다.
  • $data = array("id" => 1, "name" => "Chris", "biography" => "I am am a PHP developer");
    foreach($data as $key => $value) {    
    if(!$class->hasProperty($key)) {        
    throw new Exception($key." is not a valid property");
        } 
        if(!$class->hasMethod("get".ucfirst($key))) {        
        throw new Exception($key." is missing a getter");
        } 
        if(!$class->hasMethod("set".ucfirst($key))) {        
        throw new Exception($key." is missing a setter");
        } 
        // Make a new object to interact with
        $object = new Person(); 
        // Get the getter method and invoke it with the value in our data array
        $setter = $class->getMethod("set".ucfirst($key));    
        $ok = $setter->invoke($object, $value); 
        // Get the setter method and invoke it
        $setter = $class->getMethod("get".ucfirst($key));    
        $objValue = $setter->invoke($object); 
        // Now compare
        if($value == $objValue) {        
        echo "Getter or Setter has modified the data.\n";
        } else {        
        echo "Getter and Setter does not modify the data.\n";
       }
    }
    로그인 후 복사
  • 위 내용은 모두의 학습에 도움이 되기를 바랍니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요!

    관련 권장 사항:
  • php 웹 콘텐츠 및 이미지를 크롤링하는 방법

    PHP 가져오기 진행률 표시줄 클래스

    PHP 범위

    위 내용은 PHP의 반사 반사 메커니즘 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    관련 라벨:
    원천:php.cn
    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!