Jump to content

functions directly in arrays?


alecks

Recommended Posts

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?)

Link to comment
Share on other sites

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']);

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.