Accessing a CONST attribute of series of Classes *

Question

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 behaviour without instantiating the class?

Answer

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

?>
< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/5459/" >Accessing a CONST attribute of series of Classes< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment