0

This's my code:

$array = array(
    'id' => 1,
    'name' => 'Paul',
    'current_job' => 'coder'
);
$interface = 'interface PropertyInterface {';

foreach ($array as $key => $value) {
    $interface .= 'const '.strtoupper($key).' = '.$value.';';
}

$interface .= '}';
eval($interface);

class Foo implements PropertyInterface
{

}

when running:

var_dump(Foo::ID);

it working, return 1, but when running:

var_dump(Foo::NAME);

or:

var_dump(Foo::CURRENT_JOB);

it not working, this is error:

Use of undefined constant toan - assumed...

what's wrong? somebody can help me?

user3672775
  • 21
  • 1
  • 5
  • 1
    *what's wrong?* You're abusing the language. Can you describe what you're trying to accomplish and maybe we can help you find a better solution to your problem. –  Jun 26 '14 at 17:13
  • i want create dynamic const property for class Foo :D – user3672775 Jun 26 '14 at 17:17
  • Possible duplicate http://stackoverflow.com/questions/1203625/dynamically-generate-classes-at-runtime-in-php – Mike Jun 26 '14 at 17:24

1 Answers1

0

This is because you are concatenating $value as constant.

$interface .= 'const '.strtoupper($key).' = '.$value.';';

Above translates to:

const NAME = Paul;

You need to wrap in double quotes "'.$value.'"

$interface .= 'const '.strtoupper($key).' = "'.$value.'";';

Which translates to:

const NAME = "Paul";
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
  • 1
    `$value` is probably user input, so using `eval()` to create a dynamic class in this way is likely a very bad idea, especially since the OP seems to lack a basic understanding of things like knowing the difference between a constant and a string. – Mike Jun 26 '14 at 17:36