Php 全局变量can';无法在函数内部访问
我需要从另一个函数访问全局变量。首先,我在一个函数中为全局变量赋值。当我试图从另一个函数获取该值时,它总是返回null。这是我的密码 StockList.phpPhp 全局变量can';无法在函数内部访问,php,global-variables,global,Php,Global Variables,Global,我需要从另一个函数访问全局变量。首先,我在一个函数中为全局变量赋值。当我试图从另一个函数获取该值时,它总是返回null。这是我的密码 StockList.php <?php $_current; class StockList { public function report(){ global $_current; $_current = 10; } public function getValue(){ print_r($GLOBALS['_
<?php
$_current;
class StockList
{
public function report(){
global $_current;
$_current = 10;
}
public function getValue(){
print_r($GLOBALS['_current']);
}
}
?>
Suggestion.php
<?php
include ("StockList.php");
$stk = new StockList();
$stk->getValue();
?>
提前感谢。伙计,很难理解你在index.php中调用report()时想做什么 无论如何,在处理类时,要设置变量值,标准过程如下:
class StockList
{
public $_current;
public function setValue($value){
$this->current = $value;
}
public function getValue(){
return $this->current;
}
}
在你想使用课程的时候:
<?php
include ("StockList.php");
$stk = new StockList();
$stk->setValue(10);
$_current = $stk->getValue();
var_dump($_current);
?>
这是OOP的基本思想,这种方法的好处是:
为什么这需要是一个全局变量?为什么不能简单地使用类属性?在创建全局变量之前,不能访问它。因此,尽量避免使用全局变量。我认为全局变量应该在类中。请检查:在您的示例中,您从未调用
report()
。所以它没有设置变量。如果调用它,它将按预期工作,report()将在index.php中调用。getValue()函数是在Ajax中调用的。您能否以某种方式显示report()调用的代码?或者确保在创建类实例之后和调用getValue()之前调用了report()@但是,听起来您希望在页面之间保留值更改。如果是这样的话,你应该使用一个会话。否则,每次都必须设置该值