note 34353 added to function.eval

From: Date: Thu, 24 Jul 2003 15:36:45 +0000
Subject: note 34353 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-52576@lists.php.net to get a copy of this message
I find that one of the simplest but also most useful (in an everyday setting) ways to use eval() is to write a conditional statement inside of a switch or other control structure (if-else if-else, e.g.), and then to use eval coupled with an if statement to evaluate the expression. It's good to use when you would normally have a lot of nested if structures that *really* just decide on one thing, but have to be nested because of lots of different option possibilities. It also saves typing if structures inside of switches or other if structures over and over again. As an example, the following code might decide whether or not an authenticated user has permissions to access the current interface of a certain application: GIVEN: $interface is defined as one of 'superuser', 'admin', or 'user'; if it is undefined assume that no permission check is required $user is an array that contains an element keyed by 'class', indicating the type of user -- one of 'superuser', 'admin', or 'user' <?php // create a conditional statement if ($interface == 'superuser') $cond = "\$user['class'] == 'superuser'"; else if ($interface == 'admin') $cond = "\$user['class'] == 'admin'"; else if ($interface == 'user') $cond = "\$user['class'] == 'user'"; else $cond = '1'; // in every case, the superuser is authorized $cond .= " || \$user['class'] == 'superuser'"; // evaluate the condition $authorized = eval( "return ($cond);" ); // kick the user out if not authorized if (!$authorized) { // (redirect) } ?> ---- Manual Page -- http://www.php.net/manual/en/function.eval.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34353 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34353&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34353&report=yes

« previous php.notes (#52576) next »