Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a CONST attribute of series of Classes

Tags:

oop

php

This is how I wanted to do it which would work in PHP 5.3.0+

<?php
    class MyClass
    {
        const CONSTANT = 'Const var';        
    }

    $classname = 'MyClass';
    echo $classname::CONSTANT; // As of PHP 5.3.0
?>

But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?

like image 857
Peter Coulton Avatar asked Aug 07 '08 22:08

Peter Coulton


1 Answers

You can accomplish this without using eval in pre-5.3 code. Just use the constant function:

<?php

class MyClass
{
    const CONSTANT = 'Const var';
}

$classname = 'MyClass';
echo constant("$classname::CONSTANT");

?>
like image 84
AdamTheHutt Avatar answered Oct 23 '22 05:10

AdamTheHutt