Indrid Cold wrote:
Is there a way to call a function so the function shares the scope of the
caller?
For example, I was playing around with making a php version of the cold
fusion tag CFPARAM
What that cold fusion tag/sorta-function does is:
1) Check if a variable exists
2) If it doesn't, creat it with a default value
I could do it inline like this:
eval("if(empty(\$testVar)) \testVar=null;");
but I don't see how I could do it as a function, like say
phParam("test")
... is there any way for php to see all variables in the caller's scope
without passing them in or declaring them all global?
The good news is that you can quite easily solve the problem of passing
vars as params, with get_defined_vars, compact() and extract() :
<?php
$glo = array(1, 1, 2, 3, 5, 8);
function caller($arg1, $arg2) {
global $glo;
$loc = 33;
$arr = get_defined_vars();
// show what is defined in the current scope :
echo "<hr>\nIn caller :<br>\n"
. nl2br(var_export($arr, true)) . "<hr>\n";
// and pass all context to the callee
callee(compact(array_keys($arr)));
}
function callee($args) {
extract($args);
unset($args); // optional...
// show what is defined in the current scope :
echo "<hr>\nIn caller :<br>\n"
. nl2br(var_export(get_defined_vars(), true)) . "<hr>\n";
}
caller('meaningoflife', 42);
?>
The bad news is that if you need to share so much state, then your
design is probably a bit flawed.
My 2 cents,
Bruno