🔍 登录 注册

Php反射

大 大苹果 2017-05-25 linux 👁 3754 ⏱ 13min

ReflectionClass::__construct

(PHP 5, PHP 7)

ReflectionClass::__construct — 初始化 ReflectionClass 类

说明

public ReflectionClass::__construct( mixed $argument )

初始化新的 ReflectionClass 对象。

参数

  • argument

  • 既可以是包含类名的字符串(string)也可以是对象(object)。

返回值

返回初始化完成后的 ReflectionClass 实例。

错误/异常

如果要反射的 Class 不存在,抛出异常 ReflectionException。

范例

Example #1 ReflectionClass 的基本用法


<?php
Reflection::export(new ReflectionClass('Exception'));
?>



以上例程的输出类似于:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

参见


add a note add a note

User Contributed Notes 6 notes

3 years ago

Example of usage:
   

public static function getClassData($class)
{
    // Trying to create a new object of ReflectionClass class
    $class = new ReflectionClass($class);
    $details = sprintf('%s - %s%s%s%s%s%s%s%s',
        $class->getName(),
        $class->isInternal()     ? 'internal class,' : 'user-defined class,',
        $class->isTrait()        ? '  is trait,'  : '',
        $class->isInterface()    ? '  is interface,'  : '',
        $class->isAbstract()     ? '  is abstract,'  : '',
        $class->isFinal()        ? '  is final,'  : '',
        $class->isCloneable()    ? '  is cloneable,'  : '',
        $class->isInstantiable() ? ' is instantiable,'  : '',
        $class->isIterateable()  ? ' is iterable  : ''
    );
    return '<pre class="debug">' . rtrim($details, ',') . '</pre>';
}

5 years ago

Running the following code on Windows Vista (I know, I know), PHP 5.3.9, the ReflectionClass constructor actually throws a ReflectionException when the desired class cannot be instantiated:

<?php
    
try {
        $ReflectedClass = new ReflectionClass('NonExist');
} catch (LogicException $Exception) {
    die('Not gonna make it in here...');
} catch (ReflectionException $Exception) {
        die('Your class does not exist!');
}
?>

7 years ago

It's very useful to know that you can also use the ReflectionClass to inspect interfaces, even thouth Interfaces are not classes. Example: 

<?php 

  
interface Edible 
  
{ 
    public function 
eat(); 
  } 

  
$refl = new ReflectionClass("Edible"); 
  
$methods = $refl->getMethods(); 
?> 

[Edit by danbrown AT php DOT net - Contains a bugfix by (dbl AT bnet DOT com) on 18-AUG-2010 with the following message: "underline had to be removed for it to work ( new Reflection_Class -> new ReflectionClass )"]

danbettles at yahoo dot co dot uk 

2 years ago

To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement. 
So instead of: 
<?php 
use App\Core as Core; 
$oReflectionClass = new ReflectionClass('Core\Singleton'); 
?> 
You would type: 

<?php 
use App\Core as Core; 
$oReflectionClass = new ReflectionClass('App\Core\Singleton'); 
?>

5 years ago

Useful to know that if you pass a string into the construct and the class cannot be instantiated for some reason a SPL LogicException will be thrown. 
This code was ran on a Mac OS X 10.6.7, AMP, PHP 5.3+

<?php

    //  index.php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $logicDuh) {
        print_r($logicDuh);
    }
    
?>
Will return a deeply nested array full of useful information about the error.


3 years ago


if (is_file($classfile))
    require_once $classfile;
if (! class_exists($classname, false))
    exit('ERROR: ' . $classname . ' is not defined as a Class');

The above code is useful to tell if the class was defined.  You could also use another commentors method using Try Catch Exceptions.  But, if you do not use try blocks much, the above function based method works just fine.

    From there, you can than call:

$class = new ReflectionClass($classname);
if (! $class->isSubclassOf('PanelCommon'))
    exit("ERROR: {$classname} must extends PanelCommon");
if (! $class->isUserDefined())
    exit("ERROR: {$classname} must be user defined and not internal to PHP");
if (! $class->IsInstantiable())
    exit("ERROR: {$classname} must be IsInstantiable and not an Interface or Abstract class");
if (! $class->hasMethod('home'))
exit("ERROR: {$classname} lacks required method/function home()");
Forforth and so on.

读完了?给作者一点支持

本文采用 CC BY 4.0 协议转载 · © 大苹果

评论(0)

登录 后参与评论。

  • 还没有评论,来抢沙发。

🔗 相关文章

Mysql 表被标记为崩溃,最后一次自动化修复失败

当 MySQL 日志中出现“表被标记为崩溃且自动修复失败”的提示时,通常表示 MySQL 在启动过程中检测到某个表的文件系统或存储引擎层出现了问题。这种情况通常会导致表无法正常使用,需要手动进行修复。以下是处理这种情况的一些步骤和方法: ### 1. **查看具体错误信息** 首先,需要查看 MySQL 错误日志以获取更多的错误信息。这可以帮助确定崩溃的表和具体的问题。 ```bash # 查看 MySQL 错误日志 tail -f /var/log/mysql/error.log ``` ### 2. **修复表** 不同的存储引擎有不同的修复工具,以下是常用的修复方法: #### **使用 `myisamchk` 修复 MyISAM 表** 如果崩溃的表使用的是 MyISAM 存储引擎,可以使用 `myisamchk` 工具来修复表。 1. 停止 MySQL 服务: ```bash sudo systemctl stop mysql ``` 2. 使用 `myisamchk` 修复表:

2024/8/11👍 0

mermaid.min.js的使用及介绍

`mermaid.min.js` 是一个 JavaScript 库,用于在浏览器中轻松绘制复杂的图表和流程图。Mermaid 通过使用简单的标记语言来描述图表,使得用户无需深入学习图表绘制的底层技术即可创建专业的图形。 在这篇文章中,我们将介绍 `mermaid.min.js` 的功能、应用场景、如何在项目中使用,以及一些常用的示例。 ## Mermaid 的功能 Mermaid 支持多种类型的图表,包括但不限于: 1. **流程图(Flowchart)**: - 用于表示流程或过程中的步骤。 - 支持各种节点和连线风格。 2. **序列图(Sequence Diagram)**: - 用于表示对象之间的交互。 - 展示消息的发送和接收过程。 3. **类图(Class Diagram)**: - 用于表示类及其关系。 - 支持类的属性和方法定义。 4. **状态图(State Diagram)**: - 用于描述系统状态及其转换。 - 适用于复杂的状态机建模。 5. **甘

2024/8/9👍 0

docker之Dockerfile及docker compose配置文件的说明及使用

Docker 的配置文件对于镜像构建和容器化应用的管理至关重要。在 Docker 中,主要的配置文件是 Dockerfile 和 docker-compose.yml。Dockerfile 用于构建镜像,而 docker-compose.yml 用于定义多容器应用。下面将详细介绍这两个文件的配置选项和用法。 ## Dockerfile 配置详解 **Dockerfile** 是一个文本文件,其中包含一组指令,用于定义如何构建 Docker 镜像。以下是 Dockerfile 中常用的指令及其用法: ### FROM `FROM` 指令用于指定基础镜像,是 Dockerfile 中的第一条指令。 ```dockerfile FROM node:14 ``` 上例中,`node:14` 是官方的 Node.js 版本 14 的镜像。 ### LABEL `LABEL` 用于为镜像添加元数据,以键值对形式存在。 ```dockerfile LABEL maintainer="your-email@example.com" LABE

2024/8/9👍 0