Page 1 of 1
accesing variable of parent function
Posted: Tue Jan 08, 2008 5:39 am
by devendra-m
Code: Select all
<?
function test1()
{
$count=0;
function test2()
{
$count=1;
print($count);
}
test2();
}
print(test1());
?>
in function test2(), is it possible to access variable $count of function test1(). Because I have to check value of variable of parent function while using recursion.
Posted: Tue Jan 08, 2008 5:57 am
by Chris Corbyn
Yes it is possible. But it would have been easy enough to try yourself

Posted: Tue Jan 08, 2008 11:53 am
by feyd
There is no such thing as "parent" functions in PHP.
Posted: Tue Jan 08, 2008 2:51 pm
by superdezign
A function can only access it's parameters and global variables.
... I had no idea PHP supported nested functions, though I hardly see it as a useful 'feature.'
Posted: Tue Jan 08, 2008 9:05 pm
by feyd
superdezign wrote:A function can only access it's parameters and global variables.
... I had no idea PHP supported nested functions, though I hardly see it as a useful 'feature.'
It doesn't support nested functions. It supports the declaration of them anywhere for the most part however.
Posted: Tue Jan 08, 2008 10:54 pm
by devendra-m
In that case I think I should follow "Pass by reference" mechanism
Posted: Wed Jan 09, 2008 12:52 am
by RobertGonzalez
Why not just pass it, period?
Posted: Wed Jan 09, 2008 4:13 am
by crystal ship
Why not just pass it, period?
Are you talking about passing the value $count as parameter to the function test2() as function test2($count).
I think this will work well here
Posted: Wed Jan 09, 2008 4:23 am
by devendra-m
But I need changed value of $count inside function test2(), So I need "pass by reference"
Posted: Wed Jan 09, 2008 4:39 am
by Kieran Huggins
Check out "passing variables by association" - it might be just what you're looking for.
Posted: Wed Jan 09, 2008 7:41 am
by webspider
Kieran Huggins wrote:Check out "passing variables by association" - it might be just what you're looking for.
what does it mean by "passing variables by association"?as i know variables can be send to a function either passing by value or by reference. is it another way to pass variables to functions? how ?
Posted: Wed Jan 09, 2008 7:53 am
by superdezign
webspider wrote:what does it mean by "passing variables by association"?as i know variables can be send to a function either passing by value or by reference. is it another way to pass variables to functions? how ?
I've no idea what that is either.
You probably won't need to pass by reference though since you could always just return a value, and you definitely won't need to define that function within another, especially if recursion is what you're after.
Posted: Wed Jan 09, 2008 9:22 am
by Kieran Huggins
sorry - I meant by reference
I've been in ORM records all day

Posted: Wed Jan 09, 2008 10:28 am
by RobertGonzalez
And make sure to read up on the difference of passing by reference on PHP 4 vs. PHP 5.