View Single Post

  #3 (permalink)  
Old 03-12-2008
Shawn McKenzie
 
Posts: n/a
Default Re: Setting a variable inside a function and making it global insideaninnerfunction doesn't work?

Shawn McKenzie wrote:
> Lamonte wrote:
>> Setting a variable inside a function and making it global inside an
>> inner function doesn't work?
>>
>> Right well I have created this function:
>>
>>
Code:
>> function getForumChildrenTree( $id )
>> {
>>    $id = intval( $id );
>>    $treeResult = array(
>>        'topics' => array(),
>>        'posts' => array(),
>>        'forums' => array(),
>>    );
>>    applyForumChildrenTree( $id );
>> }
>>
>>
>> What this function does: Basically this function is set to an id of a
>> forum id, then theres a variable that stores an array. Then theres a
>> recursive function called "applyForumChildrenTree" to update the
>> "treeResult" variable, but it's not exactly working. For some reason
>> when I did print_r inside the "applyForumChildrenTree" the array is as
>> applied:
>>
>>
Quote:
>> Array
>> (
>> [forums] => Array
>> (
>> [0] => 3
>> [1] => 8
>> [2] => 5
>> )
>>
>> [topics] => Array
>> (
>> [0] => 5
>> )
>>
>> [posts] => Array
>> (
>> [0] => 5
>> )
>>
>> )
>>
>>
>> Then inside the actual function "getForumChildrenTree" I tried
>> outputting the "treeResult" array using "print_r" after the recursive
>> function "applyForumChildrenTree" as follows:
>>
>>
Code:
>> function getForumChildrenTree( $id )
>> {
>>    $id = intval( $id );
>>    $treeResult = array(
>>        'topics' => array(),
>>        'posts' => array(),
>>        'forums' => array(),
>>    );
>>    applyForumChildrenTree( $id );
>>    print_r($treeResult);
>> }
>>
>>
>> and it showed me a blank array, (default array I created) as follows:
>>
>>
Quote:
>> Array
>> (
>> [topics] => Array
>> (
>> )
>>
>> [posts] => Array
>> (
>> )
>>
>> [forums] => Array
>> (
>> )
>>
>> )
>>
>>
>> Is this a bug? I'm using PHP 5.2.4

>
> Well you haven't defined anything global in your code, unless you did
> inapplyForumChildrenTree(), in which case it needs to be global
> everywhere that you want to use it as global.
>
> Easiest way would just be to use it like this everywhere:
>
> $GLOBALS['treeResult'] = array(
> 'topics' => array(),
> 'posts' => array(),
> 'forums' => array(),
> );
>
> -Shawn


After a second look, probably a better alternate would be to have
applyForumChildrenTree() return the array, then use $treeResult =
applyForumChildrenTree( $id );

-Shawn
Reply With Quote