PHP:访问类中的现有对象
我有一个名为 Information
的预先存在的对象,其中包含登录/用户信息。我想从另一个班级访问它。我尝试谷歌搜索并搜索了很长时间......没有运气。为什么Information
对象会超出范围?
class foo() {
function display() {
print_r($Information);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于多种原因,$Information 可能超出范围。
首先,也许 $Information 是全局的,您只需要使用 global 关键字告诉 php:
其次,也许 $Information 是 foo 实例的一部分?在这种情况下,在 php 中,您需要“$this”关键字。
第三,也许 $Information 是在 display 的调用者中创建的,而 display/foo 对它一无所知。
除非您明确地将 $Information 传递给 display,或者将其作为每个 Foo 实例的成员变量,否则 display 将无法访问它。显示可以看到(1)全局变量(2)实例变量,(3)要显示的参数,(4)要显示的局部变量。没有其他内容属于 display() 的范围。
编辑以回答您的问题
是的,我所说的“全球”是指它最初被定义为“全球”。因为不在特定函数内,即:
有很多理由避免使用全局变量。关于这个主题已经写了很多文章。这是关于该主题的 stackoverflow 问题。
$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:
Second, maybe $Information is part of the foo instance? In this case, in php, you need the "$this" keyword.
Third, maybe $Information was created in the caller of display and display/foo simply know nothing about it.
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.