note 76164 deleted from function.eval by peehaa

From: Date: Mon, 09 Dec 2013 11:55:00 +0000
Subject: note 76164 deleted from function.eval by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-197851@lists.php.net to get a copy of this message
Note Submitter: pierrotevrard at gmail dot com ---- A wonderful world of eval() applications You certainly know how to simulate an array as a constant using eval(), not ? See the code below: <?php if( ! defined('MY_ARRAY') ) { define( 'MY_ARRAY' , 'return ' . var_export( array( 1, 2, 3, 4, 5 ) , true ) . ';' ); } ?> And far, far away in your code... <?php $my_array = eval( MY_ARRAY ); ?> But the grandeur of eval is when you use it to customize some method of a class : <?php if( ! class_exists( 'my_class' ) ) { class my_class { //private propreties var $_prop; var $_custom_check = 'return true;'; //of course, I want a default check code that return true //PHP4 constructor function my_class() { $this -> _prop = eval( MY_ARRAY ); } function customize_check( $code ) { $this -> _custom_check = $code; } function check( $val ) { return eval( $this -> _custom_check ); } } } $my_class = new my_class(); $check = 'return in_array( $val , $this -> _prop , true );'; $my_class -> customize_check( $check ); print '<pre>'; if( $my_class -> check( 1 ) ) { echo '1 is checked as true.' . "\n"; } else { echo '1 is checked as false.' . "\n"; } //show: 1 is checked as true. if( $my_class -> check( '1' ) ) { echo '"1" is checked as true.' . "\n"; } else { echo '"1" is checked as false.' . "\n"; } //show: "1" is checked as false. print '</pre>'; ?> The application of eval() using propreties of a class gives you so much possibilities... Of course, combinate with a safer eval code, will be better but if you use it only in your code ( for framework project by example ) that's note necessary... Have fun.

« previous php.notes (#197851) next »