Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

drupal_eval() does not allow you to access context variable. but...

Parent Feed: 

I am currently working on a project which uses the module site_user_list and I wanted to use some variables in my template. The documentation of the module said I could use the variables from the $r array but I discovered that was not working. I found someone discovered the same problem and opened an issue:
http://drupal.org/node/183379

That same person also contributed a patch but I was unhappy with it. I provided my own.

If you want to use drupal_eval() and allow the code inside that to access (read-only) some of your context variables, try this:

Let's assume you want to eval the PHP code found in the variable $code. You might consider doing like this:

$options = array('foo' => 'bar');
drupal_eval('<?php ' . $code . '?>');

This would mean that whatever PHP code found in $code would have no access to $options.

This is why I recommend this:

$options = array('foo' => 'bar');
drupal_eval('<?php $options = '. var_export($options, TRUE).'; ' . $code . '?>');

The var_export() function (php core) will create valid PHP code from your array. You assign that to another variable (could be called anything) and voila. This code will be executed and the values from your $options array becomes accessible (read-only) to your $code.
If the code inside $code tries to change the values of $options, it will NOT change the values of the real $options since it is a copy.

Author: 
RSS Tags: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web