PHP 变量全球化问题
我有一个公共对象,假设 X. 在配置文件中定义。我如何在类中的方法中使用这个对象。我认为当我在该方法中全球化 X 时,它看起来在类中。 :(
include('config.php'); //the objec X is defined here
class MyClass{
public foo(){
global $X; // I thing It is looking within the class
}
}
I have a public object Let say X. defined in a config file. How could I use this object in a method within a class. I think when I globalize X in that method its looks within the class.
:(
include('config.php'); //the objec X is defined here
class MyClass{
public foo(){
global $X; // I thing It is looking within the class
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我做了一个演示...我希望这是你想要的..
全局.php
索引.php
I have made a demo...I hope this is what you wanted..
global.php
index.php
这对我有用:
你确定你的 $X 对象是全局的吗?
This works for me:
Are you sure your $X object is global?
如果您在配置文件中以这种方式定义了
$x
:那么在函数中使用
global
就可以正常工作。或者,您也可以使用全局数组来访问变量$GLOBALS['x']
,但我不确定这种做法有多常见或建议这样做。但是,如果您在函数或类中定义了配置变量,那么它也必须有一个全局变量,例如:
If you defined
$x
in your config file in this way:then using the
global
in the function will work just fine. Alternately you could also use the global array to access the variable$GLOBALS['x']
, however I'm not sure how common or suggested that is.However, if you have your configuration variable defined inside a function or class then it would have to have a global there as well for example: