PHP: Accessing an existing object within a class
I have a pre-existing object called Information
, which contains login/user information. I would like to access this from another class. I tried Googl开发者_JAVA技巧ing and searching for ages... no luck. Why would the Information
object be out of scope?
class foo() {
function display() {
print_r($Information);
}
}
$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.
精彩评论