alecks Posted February 14, 2007 Share Posted February 14, 2007 newbie question (i think): Can functions be placed directly into arrays? ex: $array = array('example' => (is_dir(/example/example2))?print "yes":print "no"); I know this can be accomplished like this: $example = (is_dir(/example/example2))?print "yes":print "no"; $array = array('example' => $example); but I would still like to know. (ps. is the above syntax correct?) Quote Link to comment Share on other sites More sharing options...
hitman6003 Posted February 14, 2007 Share Posted February 14, 2007 Have you tried it? I would guess that it will work, but in order to execute the code you would have to store it as a string of text (if you execute it like you have it now, the array element will store the result of the "function") then use eval on the array element... $array = array( 'example' => 'is_dir(/example/example2))?print "yes":print "no";', 'example2' => 'echo "I am a test";' ); eval($array['example2']); Quote Link to comment Share on other sites More sharing options...
redarrow Posted February 14, 2007 Share Posted February 14, 2007 you can use this metod but as you going to use the statement eval be carefull ok. mixed eval ( string $code_str ) eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution. code_str does not have to contain PHP Opening tags. There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str. To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode. Also remember that variables given values under eval() will retain these values in the main script afterwards. A return statement will terminate the evaluation of the string immediately. As of PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. In case of a parse error in the evaluated code, eval() returns FALSE. In case of a fatal error in the evaluated code, the whole script exits. In PHP 3, eval() does not return a value. Quote Link to comment Share on other sites More sharing options...
alecks Posted February 14, 2007 Author Share Posted February 14, 2007 Ah, ok it works. Thanks very much Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.