PHP

Return Class Constant From Variable

PHP constant values allow you to set a variable on the class which will remain the same and is unchangeable. The difference between these constants and other variables in a class is that they are not defined with a $.

In a recent project I had a situation where I needed to get the value of a class constant, normally this isn't a problem you would just use the :: syntax to call the constant on the class.

class A
{
    const foo = 'bar';
}

echo A::foo;

The problem I had is that the constant was being set by a variable, using the example above this will take a variable with a value of foo and I want to get the constant of foo to return bar.

First I tried out the code below to get the value of foo, but this doesn't work as the constant in class A is not defined as $constant so it can not be found.

class A
{
    const foo = 'bar';
}

$constant = 'foo';
echo A::$constant;

Then I discovered the PHP constant() function, this allows you to get the value of a constant from a string.

constant('A::foo');

Now we can create a method on the class to get the constant value depending on the value we pass into it.

class A
{
    const foo = 'bar';

    public function getConstant( $const )
    {
        return constant('self::' . $const); 
    }
}

$classA = new A();

// Returns bar
echo $classA->getConstant( 'foo' );
Back to top

Leave a Reply

Your email address will not be published. Required fields are marked *