PHP 日本研討會 2024

ReflectionClass::getConstant

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getConstant取得已定義的常數

說明

public ReflectionClass::getConstant(string $name): mixed

取得已定義的常數。

參數

name

要取得的類別常數名稱。

傳回值

名稱為 name 的常數值。如果在類別中找不到該常數,則傳回 false

範例

範例 1:使用 ReflectionClass::getConstant()

<?php

class Example {
const
C1 = false;
const
C2 = 'I am a constant';
}

$reflection = new ReflectionClass('Example');

var_dump($reflection->getConstant('C1'));
var_dump($reflection->getConstant('C2'));
var_dump($reflection->getConstant('C3'));
?>

上述範例會輸出

bool(false)
string(15) "I am a constant"
bool(false)

另請參閱

新增筆記

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

6
aurelien dot tisserand at wavesoftware dot ch
11 年前
如果目標類別中不存在 $name 常數,則函式會傳回 bool(false),而不是空值或 null,而是 false (您需要使用 "===" 測試)

$constFounded = false ;
$this->currentlangClass = new ReflectionClass($langFile);
$this->currentlangClass->getConstant($constant);
if($myConst !== false){
$constFounded = true ;
}
4
Bhimsen
12 年前
"getconstant" 方法可用於取得與您正在檢查的特定類別的常數相關聯的值。
以下程式碼片段顯示了這一點
以下程式碼片段顯示了這一點

<?php
class Test{
const
ONE = "Number one";
const
TWO = "Number two";
}

$obj = new ReflectionClass( "Test" );
echo
$obj->getconstant( "ONE" )."\n";
echo
$obj->getconstant( "TWO" )."\n";

?>

輸出
Number one
Number two
To Top