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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declare a global object and add to it

Status
Not open for further replies.

timgerr

IS-IT--Management
Jan 22, 2004
364
0
0
US
Here is my problem, I am used to different languages (java,flex) where I can declare somthing and then add to it when I want. Here is my problem, I want to declare an object, run a function that will add an array to the object and then add to that object from another function. It might be easier to show you what I am trying to say:
Code:
global $test;
 $test = new stdClass;
 $test->name = 'Master';
 function AddTest()
 {
 	$arr = array();
	$a = new stdClass;
	$a->name = 'Tom';
	$arr[] = $a;
	$test->children = $arr;
 }
 
 AddTest();
 print_r($test);
This outputs
Code:
stdClass Object ( [name] => Master )
I want it to output
Code:
stdClass Object ( [name] => Master, [children] => Array ( [0] => stdClass Object ( [name] => Tom)))
Can I create a global something to add to it whenever I want?

Thanks for the read and help,
timgerr


-How important does a person have to be before they are considered assassinated instead of just murdered?
Congratulations!
 
the global keyword is a bit of a misnomer. it bring a global variable available in the local scope, it can also make a variable that exists only in the local scope, variable. read up in the manual.

it's usage is from inside areas of local scope, however. you cannot use global from the global scope.

so to access $test from your Addtest() function you must use the global keyword from within the function.

Code:
 //global $test;
 $test = new stdClass;
 $test->name = 'Master';
 function AddTest(){
    [red]global $test;[/red]
    $arr = array();
    $a = new stdClass;
    $a->name = 'Tom';
    $arr[] = $a;
    $test->children = $arr;
 }
 
 AddTest();
 print_r($test);

the alternative is to use the $GLOBALS array which will contain references to all the variables in the global scope.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top