Eval Bad Practice?

I’m in a situation where I need a variable name to address a class, but I don’t have PHP 5.3 installed/don’t feel comfortable relying on it for this client.

From http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php


<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Is it bad practice to use an eval? IE:


eval("echo ".$classname."::CONST_VALUE;");

I can also use a switch, and make a case for every variable, but I feel like eval (which I usually try to avoid) may be a better option.

Thoughts?

e39m5

Can always use some sort of protection if the value is collected from the user.


$allowedClasses = array( 'Class1', 'Class2', 'Class3' );

if( !in_array( $classname, $allowedClasses ) )
{
    die( 'Unknown class' );
}

Edit: Also, if you’re creating an object from this class, the limitation does not exist. E.g.


$class = 'MyClass';

$object = new $class;

Is perfectly valid in php 5.2

Try utilising the Reflection API.


<?php
class Foo
{
    const BAR = 'Anthony';
    const FOO = 'Sterling';
}

function get_object_constants($object_name, $specific = null){
    $obj = new ReflectionClass($object_name);
    return is_null($specific) ? $obj->getConstants() : $obj->getConstant($specific);
}

print_r(get_object_constants('Foo'));
/*
    Array
    (
        [BAR] => Anthony
        [FOO] => Sterling
    )
*/
print_r(get_object_constants('Foo', 'BAR'));
/*
    Anthony
*/