Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable scope: creating a global array within a function 1

Status
Not open for further replies.

SCelia

Programmer
Feb 27, 2002
82
CA
I have a function eval_code. In the function I have

eval($eval_str);

in $eval_str I have:

$title[] = $row['title'];

I want the array $title to be availiable to a required file later on in the page.

i.e.

eval_code($php_doc)

require('foo');

where foo uses the array $title. If you followed that, can you tell me how to do such a thing?

Thanks, Celia
 
Normally, any variables created in a function are deleted when the function ends. That's why using "global" on a local variable doesn't work. (It might be global for all I know -- until the function ends.)

But, you can create new variables within a function that persist after the function ends. Instead of referencing "$title", reference "$GLOBALS['title']".

This code snippet may help point you in the right direction. It takes the string to be eval'd, uses preg_replace to replace all local variable references to references to $GLOBALS, then evals the modified string. The value is available from outside the function.

[tt][code<?php

function evalString ($instring)
{
$instring = preg_replace ('/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/',
'$GLOBALS[&quot;$1&quot;]',
$instring);
eval ($instring);
}

evalString ('$title = 3;');

print $title;

?>
[/code][/tt]

Does this help?
______________________________________________________________________
Never forget that we are
made of the stuff of stars
 
Thanks sleipnir, that clears things up a bit.

I actually took the code out of the function becuase it solved a lot of bugs I was having. Celia
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top