In PHP, you can access a class constant dynamically in the following ways:
Using Curly Braces Syntax
In PHP 8.3+, you can access a class constant dynamically using the following syntax:
// PHP 8.3+
class Foo
{
public const BAR = 'bar';
}
$bar = 'BAR';
echo Foo::{$bar}; // 'bar'
If the result of the expression inside the curly braces ({}
) is not of type string, then a TypeError
is thrown.
If the class constant does not exist, this will throw an error:
// PHP 8.3+
class Foo {}
$bar = 'BAR';
// Error: Undefined constant Foo::BAR
echo Foo::{$bar};
Using constant()
In versions prior to PHP 8.3, you can use the constant()
function to dynamically access a class constant:
// PHP <8.3
class Foo
{
public const BAR = 'bar';
}
$bar = 'BAR';
echo constant(Foo::class . '::' . $bar);
If the class constant does not exist, this will throw an error:
// PHP 8+
class Foo {}
$bar = 'BAR';
// Error: Undefined constant Foo::BAR
echo constant(Foo::class . '::' . $bar);
Please note that in versions below PHP 8.0, accessing a non-existent class constant issues a warning (instead of throwing an error) and returns null
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.