PHP 类中的全局变量作用域
我有以下脚本
myclass.php
<?php
$myarray = array('firstval','secondval');
class littleclass {
private $myvalue;
public function __construct() {
$myvalue = "INIT!";
}
public function setvalue() {
$myvalue = $myarray[0]; //ERROR: $myarray does not exist inside the class
}
}
?>
有没有办法通过简单的声明使 $myarray 在小类中可用?如果可能的话,我不想将它作为参数传递给构造函数。
另外,我希望你实际上可以以某种方式使全局变量对 php 类可见,但这是我第一次遇到这个问题,所以我真的不知道。
I have the following script
myclass.php
<?php
$myarray = array('firstval','secondval');
class littleclass {
private $myvalue;
public function __construct() {
$myvalue = "INIT!";
}
public function setvalue() {
$myvalue = $myarray[0]; //ERROR: $myarray does not exist inside the class
}
}
?>
Is there a way to make $myarray available inside the littleclass, through simple declaration? I don't want to pass it as a parameter to the constructor if that was possible.
Additionally, I hope that you actually CAN make global variables visible to a php class in some manner, but this is my first time facing the problem so I really don't know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在
setvalue()
函数的开头包含global $myarray
。更新:
正如评论中指出的,这是不好的做法,应该避免。
更好的解决方案是:https://stackoverflow.com/a/17094513/3407923。
include
global $myarray
at the start ofsetvalue()
function.UPDATE:
As noted in the comments, this is bad practice and should be avoided.
A better solution would be this: https://stackoverflow.com/a/17094513/3407923.
在类中,您可以通过
$GLOBALS['varName'];
使用任何全局变量in a class you can use any global variable with
$GLOBALS['varName'];
构造一个新的单例类,用于存储和访问要使用的变量。
Construct a new singleton class used to store and access variables you want to use.
在课堂上您可能会使用 $GLOBALS['myarray']。
In the class you just might use $GLOBALS['myarray'].
为什么不直接使用 getter 和 setter 呢?
Why dont you just use the getter and setter for this?