PHP Reflect反射简单示例

示例源码

<?php
ini_set('display_errors',1);

// ReflectionClass
// ReflectionFunction
// ReflectionMethod
// ReflectionParameter

define("BR", "<br />");

class People
{

}

class Student
{
    private $name;
    private $year;

    public function __construct(string $name, int $year)
    {
        $this->name = $name;
        $this->year = $year;
    }

    public function getName()
    {
        echo __METHOD__ . BR;
        return $this->name;
    }

    public function seeBase(string $name, int $year)
    {
        $this->name = $name;
        $this->year = $year;
    }

    public function people(People $people, $year = 10)
    {

    }
}

function display($a, $b, People $people)
{
    echo "called" . BR;
}

$reflectionClass = new ReflectionClass(Student::class);
$obj = $reflectionClass->newInstanceArgs(["张三", 50]);   // 创建实例
echo $obj->getName() . BR;   // 调用实例类方法
echo BR . BR;

$reflectionMethod = $reflectionClass->getMethod("seeBase");
$parameters = $reflectionMethod->getParameters();   // 获取所有参数
print_r($reflectionMethod);echo BR;
foreach ($parameters as $key => $parameter) {
    echo "参数{$key}:{$parameter->getName()}" . BR;
}
echo BR . BR;

$reflectionMethod = $reflectionClass->getMethod("people");
print_r($reflectionMethod);echo BR;
$parameters = $reflectionMethod->getParameters();   // 获取所有参数
foreach ($parameters as $key => $parameter) {
    echo "参数{$key}:{$parameter->getName()}" . BR;

    // 这里就是依赖注入的核心了。
    if ($parameter->getClass() !== null) {
        echo "参数{$key}:对应的类名 = {$parameter->getClass()->getName()}" . BR;
    }

    // 检查参数是否有默认值
    if ($parameter->isDefaultValueAvailable()) {
        echo "参数{$key}:对应的默认值 = {$parameter->getDefaultValue()}" . BR;
    }
}
echo BR . BR;

$reflectionFunction = new ReflectionFunction("display");
print_r($reflectionFunction);echo BR;
$parameters = $reflectionFunction->getParameters();
foreach ($parameters as $key => $parameter) {
    echo "参数{$key}:{$parameter->getName()}" . BR;

    // 这里就是依赖注入的核心了。
    if ($parameter->getClass() !== null) {
        echo "参数{$key}:对应的类名 = {$parameter->getClass()->getName()}" . BR;
    }

    // 检查参数是否有默认值
    if ($parameter->isDefaultValueAvailable()) {
        echo "参数{$key}:对应的默认值 = {$parameter->getDefaultValue()}" . BR;
    }
}

打印结果

file

讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!