Greetings,

While creating a plugin for Profile NG module I've found that drupal_eval() doesn't return an array which is built in the evaluated code. The code like this returns an EMPTY array:

   $array = drupal_eval("<?php return array(1=>'aaa', 2=>'bbb'); ?>");

I changed the drupal_eval() body to the following and everything starts working okay:

function drupal_eval($code) {
  ob_start();
  $output = eval($code);
  ob_end_clean();
  return $output;
}

Later, I've found that guys from CCK module also don't use drupal_eval() function when they offer users to write a PHP snippet which builds an array of values for number/text fields. They just do:

    ob_start();
    $result = eval($field['allowed_values_php']);
    ...........
    ob_end_clean();

We are also going to use PHP native eval() function for our needs but I think it's a bad practice, since you guys created a drupal_eval() for such purposes. Unfortunatly, it doesn't fit these needs.

Where is the problem?

Thank you.

Comments

yched’s picture

True, we had to skip drupal_eval in CCK because of this array issue.
Views does the same for it's "view arguments php code" setting (that's where we stole the code :-) )

cburschka’s picture

drupal_eval is designed for returning text output. It catches the code's output in a buffer and appends the return value. (Or more precisely, it just prints the return value into the same buffer.)

These two commands are equivalent:

drupal_eval("<?php echo "Hello "; echo "World"; ?>");
drupal_eval("<?php echo "Hello "; return "World"; ?>");

Of course, this doesn't work with return values that are not strings. I'm not sure where your "empty array" comes from; your code should simply return the string "Array".

Now the question is whether to accept that drupal_eval is not designed for non-text return values and use native eval, or to extend drupal_eval with a flag parameter to bypass this output buffering.

drupal_eval still has one additional use, which is to serve as a wrapper to variable scope. But that is as simple as implementing _module_eval(), which wraps eval...

cburschka’s picture

Status: Active » Closed (won't fix)

drupal_eval is just not the right function to use here.