PHP function scope [duplicate]
I know this is kind of a hacky thing I'm trying here, but I'm wondering if this is even possible. is there anyway I can access the $x
variable in the following code, without passing arguments?
function foo() {
$x = 1;
return bar();
}
function bar() {
//get $x from foo here somehow?
return $x ? 'stuff' : 'other stuff';
}
I am not sure why, but you can use globals that opens up to a whole thing, but i will show you:
function foo() {
global $x;
$x = 1;
return bar();
}
function bar() {
global $x;
//get $x from foo here somehow?
return $x ? 'stuff' : 'other stuff';
}
Here is the demo: http://codepad.org/fPqUXzyC
It is always better to not use globals and just pass parameters, but if you cannot you could use globals
class baz {
private $x;
public function foo() {
$this->x = 1;
return $this->bar();
}
public function bar() {
return $this->x ? 'stuff' : 'other stuff';
}
}
You could make foo()
store the $x
value to $GLOBALS[]
or global $x;
. Other than that, nothing I can think of would do it. It would need to be purposely exposed to get it from inside another function.
If this is your code, I may recommend thinking about taking an object-oriented approach.
class Foo
{
public static $x;
public static function Foo(){
Foo::$x = 1;
return Foo::Bar();
}
public static function Bar() {
return Foo::$x ? 'stuff' : 'other stuff';
}
}
echo Foo::Foo();
Alternatively, do as others have suggested and pass $x
as a function parameter.
I know this is kind of old, and an answer has already been accepted, but wouldn't this work?
function foo()
{
$x = 1;
return bar($x);
}
function bar($x)
{
return $x ? 'stuff' : 'other stuff';
}
精彩评论