PHP Conference Japan 2024

ReflectionMethod 類別

(PHP 5, PHP 7, PHP 8)

簡介

ReflectionMethod 類別回報關於方法的資訊。

類別概要

class ReflectionMethod extends ReflectionFunctionAbstract {
/* 常數 */
public const int IS_STATIC;
public const int IS_PUBLIC;
公開 常數 整數 IS_PROTECTED
公開 常數 整數 IS_PRIVATE
公開 常數 整數 IS_ABSTRACT
公開 常數 整數 IS_FINAL
/* 屬性 */
公開 字串 $class
/* 繼承的屬性 */
公開 字串 $name
/* 方法 */
公開 __construct(物件|字串 $objectOrMethod, 字串 $method)
公開 __construct(字串 $classMethod)
公開 靜態 createFromMethodName(字串 $method): static
公開 靜態 export(字串 $class, 字串 $name, 布林值 $return = false): 字串
公開 getClosure(?物件 $object = null): Closure
公開 invoke(?物件 $object, 混合 ...$args): 混合
公開 invokeArgs(?物件 $object, 陣列 $args): 混合
公開 isFinal(): 布林值
公開 setAccessible(布林值 $accessible):
公開 __toString(): 字串
/* 繼承的方法 */
}

屬性

name

方法名稱

class

類別名稱

預定義常數

ReflectionMethod 修飾符

ReflectionMethod::IS_STATIC 整數

表示該方法為靜態方法。在 PHP 7.4.0 之前,其值為 1

ReflectionMethod::IS_PUBLIC 整數

表示該方法為公開方法。在 PHP 7.4.0 之前,其值為 256

ReflectionMethod::IS_PROTECTED 整數

表示該方法為保護方法。在 PHP 7.4.0 之前,其值為 512

ReflectionMethod::IS_PRIVATE 整數

表示該方法為私有方法。在 PHP 7.4.0 之前,其值為 1024

ReflectionMethod::IS_ABSTRACT 整數

表示該方法為抽象方法。在 PHP 7.4.0 之前,其值為 2

ReflectionMethod::IS_FINAL 整數

表示該方法為最終方法。在 PHP 7.4.0 之前,其值為 4

注意事項:

這些常數的值可能會在不同 PHP 版本之間有所變更。建議始終使用常數,而不要直接依賴數值。

更新日誌

版本 說明
8.4.0 類別常數現在已加入型別提示。
8.0.0 ReflectionMethod::export() 已移除。

目錄

新增筆記

使用者貢獻的筆記 2 則筆記

webseiten dot designer at googlemail dot com
13 年前
請注意,公開成員 $class 包含定義 method 的類別名稱。

<?php
class A {public function __construct() {}}
class
B extends A {}

$method = new ReflectionMethod('B', '__construct');
echo
$method->class; // 顯示 'A'
?>
匿名
4 年前
當類別的建構子依賴其他類別(使用型別提示)時,我們可以在類別中建立「自動依賴注入器」。

<?php

類別 Dependence1 {
函式
foo() {
echo
"foo";
}
}

類別
Dependence2 {
函式
foo2() {
echo
"foo2";
}
}

最終類別
myClass
{
私有
$dep1;
私有
$dep2;

公開函式
__construct(
Dependence1 $dependence1,
Dependence2 $dependence2
)
{
$this->dep1 = $dependence1;
$this->dep2 = $dependence2;
}

}

// 自動依賴注入 (類別)

$constructor = new ReflectionMethod(myClass::class, '__construct');
$parameters = $constructor->getParameters();

$dependences = [];
foreach (
$parameters as $parameter) {
$dependenceClass = (string) $parameter->getType();
$dependences[] = new $dependenceClass();
}

$instance = new myClass(...$dependences);
var_dump($instance);

?>

結果:

object(myClass)#6 (2) {
["dep1":"myClass":private]=>
object(Dependence1)#4 (0) {
}
["dep2":"myClass":private]=>
object(Dependence2)#5 (0) {
}
}
To Top