찾다
백엔드 개발PHP 튜토리얼PHP 리플렉션 클래스 ReflectionClass_php 스킬 활용 분석

이 글의 예에서는 PHP 리플렉션 클래스인 ReflectionClass의 사용법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

먼저 코드를 살펴보겠습니다.

/**
 * @name PHP反射API--利用反射技术实现的插件系统架构
 * @author :PHPCQ.COM
 */
interface Iplugin
{
 public static
 function getName();
}
function findPlugins()
{
 $plugins = array();
 foreach(get_declared_classes() as $class)
 {
  $reflectionClass = new ReflectionClass($class);
  if ($reflectionClass - > implementsInterface('Iplugin'))
  {
   $plugins[] = $reflectionClass;
  }
 }
 return $plugins;
}
function computeMenu()
{
 $menu = array();
 foreach(findPlugins() as $plugin)
 {
  if ($plugin - > hasMethod('getMenuItems'))
  {
   $reflectionMethod = $plugin - > getMethod('getMenuItems');
   if ($reflectionMethod - > isStatic())
   {
    $items = $reflectionMethod - > invoke(null);
   }
   else
   {
    $pluginInstance = $plugin - > newInstance();
    $items = $reflectionMethod - > invoke($pluginInstance);
   }
   $menu = array_merge($menu, $items);
  }
 }
 return $menu;
}
function computeArticles()
{
 $articles = array();
 foreach(findPlugins() as $plugin)
 {
  if ($plugin - > hasMethod('getArticles'))
  {
   $reflectionMethod = $plugin - > getMethod('getArticles');
   if ($reflectionMethod - > isStatic())
   {
    $items = $reflectionMethod - > invoke(null);
   }
   else
   {
    $pluginInstance = $plugin - > newInstance();
    $items = $reflectionMethod - > invoke($pluginInstance);
   }
   $articles = array_merge($articles, $items);
  }
 }
 return $articles;
}
require_once('plugin.php');
$menu = computeMenu();
$articles = computeArticles();
print_r($menu);
print_r($articles);

plugin.php 코드는 다음과 같습니다.

<&#63;php
class MycoolPugin implements Iplugin
{
 public static
 function getName()
 {
  return 'MycoolPlugin';
 }
 public static
 function getMenuItems()
 {
  return array(array('description' => 'MycoolPlugin', 'link' => '/MyCoolPlugin'));
 }
 public static
 function getArticles()
 {
  return array(array('path' => '/MycoolPlugin', 'title' => 'This is a really cool article', 'text' => xxxxxxxxx));
 }
}

위 코드는 PHP Reflection 클래스를 적용한 것입니다.

PHP 리플렉션 클래스란 이름에서 알 수 있듯이 클래스 매핑으로 이해될 수 있습니다.

예:

class fuc { //定义一个类
 static
 function ec() {
  echo '我是一个类';
 }
}
$class=new ReflectionClass('fuc'); //建立 fuc这个类的反射类

Reflection Class $class에 대한 내용은 매뉴얼을 확인하시면 되지만 여기서는 자세히 설명하지 않겠습니다

$fuc=$class->newInstance(); //相当于实例化 fuc 类
$fuc->ec(); //执行 fuc 里的方法ec
/*最后输出:我是一个类*/

더욱 고급 용도도 있습니다

$ec=$class->getmethod('ec'); //获取fuc 类中的ec方法
$fuc=$class->newInstance(); //实例化
$ec->invoke($fuc);   //执行ec 方法

위의 과정은 익숙할 것입니다. 사실 객체를 호출하는 방법과 비슷합니다

단지 메소드가 앞에 있고 객체가 뒤에 있는 것뿐입니다.

보충 : 이 웹사이트의 온라인 PHP 코드 서식 도구를 추천합니다. 이 도구를 사용하면 독자가 온라인으로 서식이 지정된 압축 PHP 코드를 읽을 수 있어 편리하고 실용적입니다 !

php 코드 온라인 서식 지정 및 미화 도구:
http://tools.jb51.net/code/phpformat

더 많은 PHP 관련 콘텐츠에 관심이 있는 독자는 이 사이트의 특별 주제를 확인할 수 있습니다. "PHP 배열(Array) 작업 기술 종합 모음", "PHP 정렬 요약 알고리즘", " PHP에서 일반적으로 사용되는 순회 알고리즘 및 기술 요약", "PHP 데이터 구조 및 알고리즘 튜토리얼", "PHP 프로그래밍 알고리즘 요약", "PHP 수학 연산 스킬 요약", "PHP 정규식 사용법 요약", "PHP 연산 및 연산자 사용법 요약", "php string(string) 사용법 요약" 및 "일반적인 PHP 데이터베이스 조작 기술 요약"

이 기사가 PHP 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?May 08, 2025 am 12:21 AM

TheBesteptroachForendingeMailsInphPisusingThephPmailerlibraryDuetoitsReliability, featurerichness 및 reaseofuse.phpmailersupportssmtp, proversDetailErrorHandling, supportSattachments, andenhancessecurity.foroptimalu

PHP의 종속성 주입을위한 모범 사례PHP의 종속성 주입을위한 모범 사례May 08, 2025 am 12:21 AM

의존성 주입 (DI)을 사용하는 이유는 코드의 느슨한 커플 링, 테스트 가능성 및 유지 관리 가능성을 촉진하기 때문입니다. 1) 생성자를 사용하여 종속성을 주입하고, 2) 서비스 로케이터 사용을 피하고, 3) 종속성 주입 컨테이너를 사용하여 종속성을 관리하고, 4) 주입 종속성을 통한 테스트 가능성을 향상 시키십시오.

PHP 성능 튜닝 팁 및 요령PHP 성능 튜닝 팁 및 요령May 08, 2025 am 12:20 AM

phpperformancetuningiscrucialbecauseitenhancesspeedandefficies, thearevitalforwebapplications.1) cachingsdatabaseloadandimprovesResponsetimes.2) 최적화 된 databasequerieseiesecessarycolumnsingpeedsupedsupeveval.

PHP 이메일 보안 : 이메일 보내기 모범 사례PHP 이메일 보안 : 이메일 보내기 모범 사례May 08, 2025 am 12:16 AM

theBestPracticesForendingEmailsSecurelyPinphPinclude : 1) usingecureconfigurations와 whithsmtpandstarttlSencryption, 2) 검증 및 inputSpreverventInseMeStacks, 3) 암호화에 대한 암호화와 비도시를 확인합니다

성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?May 08, 2025 am 12:08 AM

tooptimizephPapplicationsperperperperperperperperperferferferferferferferferferferperferferperferperperferferfercations.1) ubsicationScachingwithApcuTeDucedAtaFetchTimes.2) 최적화 된 ABASEABASES.3)

PHP의 종속성 주입이란 무엇입니까?PHP의 종속성 주입이란 무엇입니까?May 07, 2025 pm 03:09 PM

expendencyInphpisaDesignpatternpattern thatenhances-flexibility, testability 및 maintainabilitable externaldenciestoclasses.itallowsforloosecoupling, easiertesting throughmocking 및 modulardesign, berrequirecarefultructuringtoavoid-inje

최고의 PHP 성능 최적화 기술최고의 PHP 성능 최적화 기술May 07, 2025 pm 03:05 PM

PHP 성능 최적화는 다음 단계를 통해 달성 할 수 있습니다. 1) 스크립트 상단에 require_once 또는 include_once를 사용하여 파일로드 수를 줄입니다. 2) 데이터베이스 쿼리 수를 줄이기 위해 전처리 문 및 배치 처리를 사용하십시오. 3) Opcode 캐시에 대한 Opcache 구성; 4) PHP-FPM 최적화 프로세스 관리를 활성화하고 구성합니다. 5) CDN을 사용하여 정적 자원을 배포합니다. 6) 코드 성능 분석을 위해 Xdebug 또는 Blackfire를 사용하십시오. 7) 배열과 같은 효율적인 데이터 구조를 선택하십시오. 8) 최적화 실행을위한 모듈 식 코드를 작성하십시오.

PHP 성능 최적화 : Opcode 캐싱 사용PHP 성능 최적화 : Opcode 캐싱 사용May 07, 2025 pm 02:49 PM

opCodeCachingsIntIficInlyIntImeRimproveSphpperformanceCachingCompileDCode, retingServerLoadandResponsEtimes.1) itStoresCompyledPhpCodeInMemory, BYPASSINGPARSINGCOMPILING.2) UseOpCacheSettingParametersInphP.Ini, likeMoryConsAncme AD

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경