0

I have a pre-existing object called Information, which contains login/user information. I would like to access this from another class. I tried Googling and searching for ages... no luck. Why would the Information object be out of scope?

class foo() {
 function display() {
   print_r($Information);
 }
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Mike
  • 763
  • 9
  • 20

1 Answers1

1

$Information could be out of scope for many reasons.

First, maybe $Information is global and you just need to tell php with the global keyword:

class foo() {
 function display() {
   global $Information
   print_r($Information);
 }
}

Second, maybe $Information is part of the foo instance? In this case, in php, you need the "$this" keyword.

class foo() {
 function display() {       
   print_r($this->Information);
 }
}

Third, maybe $Information was created in the caller of display and display/foo simply know nothing about it.

function bar() 
{
   $Information = new $information;
   $a = new Foo();
   $a->display();
{

Unless you explicitely pass $Information to display, or make it a member variable of each Foo instance, display won't be able to access it. display can see (1) global variables (2) instance variables, (3) parameters to display, and (4) variables local to display. Nothing else is within the scope of display().

Edits to answer your questions Yes by global I mean it was initially defined as global. As in not within a specific function ie:

There's plenty of reasons to avoid globals. Plenty has been written on the topic. Here's a stackoverflow question on the topic.

Community
  • 1
  • 1
Doug T.
  • 64,223
  • 27
  • 138
  • 202
  • Thank you! The first way I had it solved was to get one of Information's properties outside the class and then use the global keyword to access that variable. If you don't mind, what do you mean when you say *$Information is global*, as in.. when it was defined initially it was global? Also, are there any MAIN reasons I should avoid using global in the future? PS: I did *global $Information* and it worked. – Mike Jan 30 '11 at 03:20