ReflectionClass::getConstant

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getConstantGets defined constant

Description

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

Gets the defined constant.

Parameters

name

The name of the class constant to get.

Return Values

Value of the constant with the name name. Returns false if the constant was not found in the class.

Examples

Example #1 Usage of 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'));
?>

The above example will output:

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

See Also

add a note add a note

User Contributed Notes 2 notes

up
5
aurelien dot tisserand at wavesoftware dot ch
10 years ago
If the $name constant doesn't exist in the targetted class the function returns bool(false), not empty nor null but false (you to test with "==="

$constFounded = false ;
$this->currentlangClass = new ReflectionClass($langFile);
$this->currentlangClass->getConstant($constant);
if($myConst !== false){
              $constFounded = true ;
}
up
3
Bhimsen
11 years ago
The "getconstant" method can be used to get the value associated with a constant
of a particular class that you are examining.
The following code snippet shows this:

<?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";
   
?>

output:
Number one
Number two
To Top