2017-02-15 128 views
0

我需要从另一个函数访问全局变量。首先,我已经在一个函数中将值赋给了全局变量。当我试图从另一个函数获取该值时,它总是返回null。在这里我的代码是全局变量不能在函数内部访问

StockList.php

<?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(); 

?> 

在此先感谢。

+0

为什么这需要是一个全局变量?为什么你不能简单地使用类属性? –

+0

在创建之前,您无法访问全局变量。这样说,尽量避免全局。 – Andrew

+0

我觉得全局变量应该在类内 –

回答

0

人,其很难理解什么是你想为你说你有人称报告()在你的index.php 不管怎么说,带班打交道时,要设置变量值做,标准程序如下:

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的基本思路,这种方法的好处是:

  1. 您可以动态设置$ _current的值。

  2. 您的getValue()函数不是专用于打印变量的值,这就是为什么您可以使用该函数仅用于获取该值,然后做任何您想要的值。

+0

report()在index.php中被调用。 getValue()函数在Ajax中调用。 – balaraman

+0

你能以某种方式显示report()调用的代码吗?或者确保你在调用getValue()之前调用了class()之后调用了report()。 – Learner

+0

@balaraman这听起来像是你期望在页面中保留价值变化。如果是这种情况,你应该使用会话。否则,您必须每次都设置该值 – Machavity