note 76164 added to function.eval

From: Date: Tue, 03 Jul 2007 15:58:15 +0000
Subject: note 76164 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-128183@lists.php.net to get a copy of this message
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. ---- Server IP: 195.26.5.11 Probable Submitter: 85.93.207.16 ---- Manual Page -- http://www.php.net/manual/en/function.eval.php Edit -- https://master.php.net/note/edit/76164 Del: integrated -- https://master.php.net/note/delete/76164/integrated Del: useless -- https://master.php.net/note/delete/76164/useless Del: bad code -- https://master.php.net/note/delete/76164/bad+code Del: spam -- https://master.php.net/note/delete/76164/spam Del: non-english -- https://master.php.net/note/delete/76164/non-english Del: in docs -- https://master.php.net/note/delete/76164/in+docs Del: other reasons-- https://master.php.net/note/delete/76164 Reject -- https://master.php.net/note/reject/76164 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#128183) next »