类内的PHP全局变量作用域 [英] PHP global variable scope inside a class
问题描述
我有以下脚本
myclass.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在littleclass内部可用?如果可能的话,我不想将其作为参数传递给构造函数。
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.
此外,我希望您实际上可以使全局变量对php类可见某种程度上,但这是我第一次遇到这个问题,所以我真的不知道。
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.
推荐答案
include 全局$ myarray
在 setvalue()
函数的开头。
include global $myarray
at the start of setvalue()
function.
public function setvalue() {
global $myarray;
$myvalue = $myarray[0];
}
更新:
如评论中所述,这是一种不好的做法,应该避免。
更好的解决方案是: https://stackoverflow.com/a/17094513/3407923 。
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.
这篇关于类内的PHP全局变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!