当前位置: 首页 > 编程文章 >

PHP类与反射API详解:验证、调用与元数据检查

PHP类与反射API详解:验证、调用与元数据检查

作者:许舟时间:2025-03-04 09:58:29浏览:460

本文介绍PHP中用于检查和操作类的内置函数及Reflection API。通过class_exists、get_class等函数可验证类存在性及对象类型;利用__call魔术方法实现动态方法调用并传递参数。Reflection API能深入剖析类结构,获取属性、方法及构造函数参数的详细信息,比var_dump提供更清晰的继承与方法来源视图。

本文目录收起

PHP类操作与反射API概述

本示例解析PHP面向对象编程中的类操作与反射API应用,供读者参考学习。

基础类知识回顾

使用class_exists函数检测类是否已定义


<?php
// TaskRunner.php
$classname = "Task";
$path = "tasks/{$classname}.php";
if ( ! file_exists( $path ) ) {
  throw new Exception( "No such file as {$path}" ); //抛出异常,类文件不存在
}
require_once( $path );
$qclassname = "tasks\\$classname";
if ( ! class_exists( $qclassname ) ) {
  throw new Exception( "No such class as $qclassname" ); //抛出异常,类不存在Fatal error: Uncaught exception 'Exception' with message 'No such class as tasks\Task'
Stack trace:
#0 {main}
}
$myObj = new $qclassname();
$myObj->doSpeak();
?>

利用get_class获取对象所属类名,结合instanceof运算符判断对象实例归属


<?php
class CdProduct {}
function getProduct() {
  return new CdProduct(  "Exile on Coldharbour Lane",
                "The", "Alabama 3", 10.99, 60.33 ); // 返回一个类对象
}
$product = getProduct();
if ( get_class( $product ) == 'CdProduct' ) {
  print "\$product is a CdProduct object\n";
}
?>
<?php
class CdProduct {}
function getProduct() {
  return new CdProduct(  "Exile on Coldharbour Lane",
                "The", "Alabama 3", 10.99, 60.33 );
}
$product = getProduct();
if ( $product instanceof CdProduct ) {
  print "\$product is a CdProduct object\n";
}
?>

get_class_methods返回类中所有public方法的列表,默认仅包含公有方法,无法获取protected和private修饰的方法。


<?php
class CdProduct {
  function __construct() { }
  function getPlayLength() { }
  function getSummaryLine() { }
  function getProducerFirstName() { }
  function getProducerMainName() { }
  function setDiscount() { }
  function getDiscount() { }
  function getTitle() { }
  function getPrice() { }
  function getProducer() { }
}
print_r( get_class_methods( 'CdProduct' ) );
?>

输出结果如下:


Array
(
  [0] => __construct
  [1] => getPlayLength
  [2] => getSummaryLine
  [3] => getProducerFirstName
  [4] => getProducerMainName
  [5] => setDiscount
  [6] => getDiscount
  [7] => getTitle
  [8] => getPrice
  [9] => getProducer
)

更多类型验证示例


<?php
class ShopProduct {}
interface incidental {};
class CdProduct extends ShopProduct implements incidental {
  public $coverUrl;
  function __construct() { }
  function getPlayLength() { }
  function getSummaryLine() { }
  function getProducerFirstName() { }
  function getProducerMainName() { }
  function setDiscount() { }
  function getDiscount() { }
  function getTitle() { return "title\n"; }
  function getPrice() { }
  function getProducer() { }
}
function getProduct() {
  return new CdProduct();
}
$product = getProduct(); // acquire an object
$method = "getTitle";   // define a method name
print $product->$method(); // invoke the method
if ( in_array( $method, get_class_methods( $product ) ) ) {
  print $product->$method(); // invoke the method
}
if ( is_callable( array( $product, $method) ) ) {
  print $product->$method(); // invoke the method
}
if ( method_exists( $product, $method ) ) {
  print $product->$method(); // invoke the method
}
print_r( get_class_vars( 'CdProduct' ) );
if ( is_subclass_of( $product, 'ShopProduct' ) ) {
  print "CdProduct is a subclass of ShopProduct\n";
}
if ( is_subclass_of( $product, 'incidental' ) ) {
  print "CdProduct is a subclass of incidental\n";
}
if ( in_array( 'incidental', class_implements( $product )) ) {
  print "CdProduct is an interface of incidental\n";
}
?>

输出结果如下:


title
title
title
title
Array
(
  [coverUrl] =>
)
CdProduct is a subclass of ShopProduct
CdProduct is a subclass of incidental
CdProduct is an interface of incidental

__call魔术方法的应用


<?php
class OtherShop {
  function thing() {
    print "thing\n";
  }
  function andAnotherthing() {
    print "another thing\n";
  }
}
class Delegator {
  private $thirdpartyShop;
  function __construct() {
    $this->thirdpartyShop = new OtherShop();
  }
  function __call( $method, $args ) { // 当调用未命名方法时执行call方法
    if ( method_exists( $this->thirdpartyShop, $method ) ) {
      return $this->thirdpartyShop->$method( );
    }
  }
}
$d = new Delegator();
$d->thing();
?>

输出结果如下:

thing

在动态调用中传递参数


<?php
class OtherShop {
  function thing() {
    print "thing\n";
  }
  function andAnotherthing( $a, $b ) {
    print "another thing ($a, $b)\n";
  }
}
class Delegator {
  private $thirdpartyShop;
  function __construct() {
    $this->thirdpartyShop = new OtherShop();
  }
  function __call( $method, $args ) {
    if ( method_exists( $this->thirdpartyShop, $method ) ) {
      return call_user_func_array(
            array( $this->thirdpartyShop,
              $method ), $args );
    }
  }
}
$d = new Delegator();
$d->andAnotherThing( "hi", "hello" );
?>

输出结果如下:

another thing (hi, hello)

Reflection反射API详解

fullshop.php文件内容


<?php
class ShopProduct {
  private $title;
  private $producerMainName;
  private $producerFirstName;
  protected $price;
  private $discount = 0;
  public function __construct(  $title, $firstName,
              $mainName, $price ) {
    $this->title       = $title;
    $this->producerFirstName = $firstName;
    $this->producerMainName = $mainName;
    $this->price       = $price;
  }
  public function getProducerFirstName() {
    return $this->producerFirstName;
  }
  public function getProducerMainName() {
    return $this->producerMainName;
  }
  public function setDiscount( $num ) {
    $this->discount=$num;
  }
  public function getDiscount() {
    return $this->discount;
  }
  public function getTitle() {
    return $this->title;
  }
  public function getPrice() {
    return ($this->price - $this->discount);
  }
  public function getProducer() {
    return "{$this->producerFirstName}".
        " {$this->producerMainName}";
  }
  public function getSummaryLine() {
    $base = "{$this->title} ( {$this->producerMainName}, ";
    $base .= "{$this->producerFirstName} )";
    return $base;
  }
}
class CdProduct extends ShopProduct {
  private $playLength = 0;
  public function __construct(  $title, $firstName,
              $mainName, $price, $playLength=78 ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price );
    $this->playLength = $playLength;
  }
  public function getPlayLength() {
    return $this->playLength;
  }
  public function getSummaryLine() {
    $base = parent::getSummaryLine();
    $base .= ": playing time - {$this->playLength}";
    return $base;
  }
}
class BookProduct extends ShopProduct {
  private $numPages = 0;
  public function __construct(  $title, $firstName,
              $mainName, $price, $numPages ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price );
    $this->numPages = $numPages;
  }
  public function getNumberOfPages() {
    return $this->numPages;
  }
  public function getSummaryLine() {
    $base = parent::getSummaryLine();
    $base .= ": page count - {$this->numPages}";
    return $base;
  }
  public function getPrice() {
    return $this->price;
  }
}
/*
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 );
print $product1->getSummaryLine()."\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
print $product2->getSummaryLine()."\n";
*/
?>
<?php
require_once "fullshop.php";
$prod_class = new ReflectionClass( 'CdProduct' );
Reflection::export( $prod_class );
?>

输出结果如下:


Class [  class CdProduct extends ShopProduct ] {
 @@ D:\xampp\htdocs\popp-code\5\fullshop.php 53-73
 - Constants [0] {
 }
 - Static properties [0] {
 }
 - Static methods [0] {
 }
 - Properties [2] {
  Property [  private $playLength ]
  Property [  protected $price ]
 }
 - Methods [10] {
  Method [  public method __construct ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 56 - 61
   - Parameters [5] {
    Parameter #0 [  $title ]
    Parameter #1 [  $firstName ]
    Parameter #2 [  $mainName ]
    Parameter #3 [  $price ]
    Parameter #4 [  $playLength = 78 ]
   }
  }
  Method [  public method getPlayLength ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 63 - 65
  }
  Method [  public method getSummaryLine ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 67 - 71
  }
  Method [  public method getProducerFirstName ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 17 - 19
  }
  Method [  public method getProducerMainName ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 21 - 23
  }
  Method [  public method setDiscount ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 25 - 27
   - Parameters [1] {
    Parameter #0 [  $num ]
   }
  }
  Method [  public method getDiscount ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 29 - 31
  }
  Method [  public method getTitle ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 33 - 35
  }
  Method [  public method getPrice ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 37 - 39
  }
  Method [  public method getProducer ] {
   @@ D:\xampp\htdocs\popp-code\5\fullshop.php 41 - 44
  }
 }
}

点评:Reflection API能透彻展示类的内部结构,优于var_dump。它能清晰显示属性、父类继承关系、方法来源(自身定义、重写或继承),一目了然。

查看类的详细数据


<?php
require_once("fullshop.php");
function classData( ReflectionClass $class ) {
 $details = "";
 $name = $class->getName();
 if ( $class->isUserDefined() ) {
  $details .= "$name is user defined\n";
 }
 if ( $class->isInternal() ) {
  $details .= "$name is built-in\n";
 }
 if ( $class->isInterface() ) {
  $details .= "$name is interface\n";
 }
 if ( $class->isAbstract() ) {
  $details .= "$name is an abstract class\n";
 }
 if ( $class->isFinal() ) {
  $details .= "$name is a final class\n";
 }
 if ( $class->isInstantiable() ) {
  $details .= "$name can be instantiated\n";
 } else {
  $details .= "$name can not be instantiated\n";
 }
 return $details;
}
$prod_class = new ReflectionClass( 'CdProduct' );
print classData( $prod_class );
?>

输出结果如下:

CdProduct is user defined CdProduct can be instantiated

查看方法的详细数据


<?php
require_once "fullshop.php";
$prod_class = new ReflectionClass( 'CdProduct' );
$methods = $prod_class->getMethods();
foreach ( $methods as $method ) {
 print methodData( $method );
 print "\n----\n";
}
function methodData( ReflectionMethod $method ) {
 $details = "";
 $name = $method->getName();
 if ( $method->isUserDefined() ) {
  $details .= "$name is user defined\n";
 }
 if ( $method->isInternal() ) {
  $details .= "$name is built-in\n";
 }
 if ( $method->isAbstract() ) {
  $details .= "$name is abstract\n";
 }
 if ( $method->isPublic() ) {
  $details .= "$name is public\n";
 }
 if ( $method->isProtected() ) {
  $details .= "$name is protected\n";
 }
 if ( $method->isPrivate() ) {
  $details .= "$name is private\n";
 }
 if ( $method->isStatic() ) {
  $details .= "$name is static\n";
 }
 if ( $method->isFinal() ) {
  $details .= "$name is final\n";
 }
 if ( $method->isConstructor() ) {
  $details .= "$name is the constructor\n";
 }
 if ( $method->returnsReference() ) {
  $details .= "$name returns a reference (as opposed to a value)\n";
 }
 return $details;
}
?>

输出结果如下:


__construct is user defined
__construct is public
__construct is the constructor
----
getPlayLength is user defined
getPlayLength is public
----
getSummaryLine is user defined
getSummaryLine is public
----
getProducerFirstName is user defined
getProducerFirstName is public
----
getProducerMainName is user defined
getProducerMainName is public
----
setDiscount is user defined
setDiscount is public
----
getDiscount is user defined
getDiscount is public
----
getTitle is user defined
getTitle is public
----
getPrice is user defined
getPrice is public
----
getProducer is user defined
getProducer is public

获取构造函数的参数配置情况


<?php
require_once "fullshop.php";
$prod_class = new ReflectionClass( 'CdProduct' );
$method = $prod_class->getMethod( "__construct" );
$params = $method->getParameters();
foreach ( $params as $param ) {
  print argData( $param )."\n";
}
function argData( ReflectionParameter $arg ) {
 $details = "";
 $declaringclass = $arg->getDeclaringClass();
 $name = $arg->getName();
 $class = $arg->getClass();
 $position = $arg->getPosition();
 $details .= "\$$name has position $position\n";
 if ( ! empty( $class ) ) {
  $classname = $class->getName();
  $details .= "\$$name must be a $classname object\n";
 }
 if ( $arg->isPassedByReference() ) {
  $details .= "\$$name is passed by reference\n";
 }
 if ( $arg->isDefaultValueAvailable() ) {
  $def = $arg->getDefaultValue();
  $details .= "\$$name has default: $def\n";
 }
 if ( $arg->allowsNull() ) {
  $details .= "\$$name can be null\n";
 }
 return $details;
}
?>

输出结果如下:


$title has position 0
$title can be null
$firstName has position 1
$firstName can be null
$mainName has position 2
$mainName can be null
$price has position 3
$price can be null
$playLength has position 4
$playLength has default: 78
$playLength can be null

希望上述内容对您的PHP程序设计有所帮助。

上一篇
PHP面向对象程序设计组合模式与装饰模式详解

本文详解PHP中的组合模式与装饰模式。组合模式通过单根继承体系让不同职责的集合协同工作,如军队整合成员输出火力,支持动态增删组件且无需大范围修改代码。装饰模式利用组合与委托替代单纯继承,灵活扩展对象功能,例如在不创建新类的情况下为钻石土地添加污染属性,实现递归式的功能叠加。

下一篇
PHP面向对象高级特性:静态、接口、抽象类与魔术方法详解

本文详解PHP面向对象编程中的高级特性,涵盖静态属性与方法调用、self与this的区别、常量定义、接口约束及抽象类规范。深入解析final关键字对类和方法的限制作用,以及析构函数、__clone、__toString等魔术方法的具体行为与应用场景,帮助开发者掌握核心机制。

相关文章

更多
PHP反射API插件系统架构示例

本文分享了利用 PHP 反射 API 构建插件系统的技术实例。通过反射机制,开发者可以动态分析类结构并实现松耦合的插件架构,为相关开发提供参考。

2025.03.19 875
PHP反射机制详解:从原理到代码实战

本文深入解析PHP5引入的Reflection功能,阐述如何通过反射API在运行时分析类的结构。通过Person类示例,演示如何获取私有/受保护属性、提取DocBlock注释以及动态实例化和执行方法,帮助开发者构建可扩展的应用程序。

2025.05.26 591
PHP反射API实现可选接口插件机制

在PHP插件开发中,强制实现所有接口方法会导致大量无用代码。利用反射API的ReflectionClass类,可在运行时通过get_declared_classes()获取已加载类,并检测其是否实现了特定接口及具体方法。对于静态方法直接调用invoke(null),非静态方法则需先实例化再调用invoke,从而实现灵活的功能扩展。

2026.04.11 423
PHP反射API详解:从基础用法到动态代理实战

本文介绍PHP反射API的核心功能,通过ReflectionClass获取类的属性与方法信息。结合Person类实例演示如何导出对象结构,并探讨利用反射实现Hook机制与动态代理的实际应用场景。

2025.08.05 344
PHP面向对象核心概念与特性详解

本文梳理了PHP5引入的面向对象编程核心特性。内容涵盖类型提示、继承机制、静态成员访问、抽象类与接口的定义规范,以及异常处理体系。重点解析了__get、__set等拦截器(魔术方法)的实现原理与clone对象的引用差异,并介绍了__autoload自动加载策略、动态类调用及反射API在运行时分析类结构中的应用。

2025.06.01 107
PHP面向对象反射机制详解与实例演示

本文深入解析PHP中的反射功能,阐述其作为操纵元模型API的核心价值。通过具体代码实例,展示如何利用ReflectionClass在运行状态下提取类的属性、方法及注释信息,并演示动态实例化对象及调用方法的完整流程,帮助开发者构建可扩展的复杂应用。

2026.01.03 300

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。