0

I need to access the global variable from another function. First I have assigned the value to global variable in one function. When I am trying to get that value from another function, it always returns null. Here my code is

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

?>

Thanks in advance.

balaraman
  • 397
  • 1
  • 7
  • 21

1 Answers1

0

Man, its hard to understand what are you trying to do as you said you have called report() in your index.php Anyways, when dealing with classes, to set variable values, standard procedure is as following:

class StockList
{
  public $_current;
  public function setValue($value){
    $this->current = $value;
  }

  public function getValue(){
     return $this->current;
  }
}

And after whenever you wanna use the class:

<?php
   include ("StockList.php");
   $stk = new StockList();  
   $stk->setValue(10);
   $_current = $stk->getValue();
   var_dump($_current);
?>

This is basic idea of OOP, benefits of this approach are:

  1. You can dynamically set value of $_current.

  2. Your getValue() function is not dedicated for printing the value of the variable, thats why you can use that function only for getting the value and then do whatever you want with it.

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • The report() is called in the index.php. The getValue() function is called in Ajax. – balaraman Feb 15 '17 at 13:21
  • can you somehow show the code for report() calling? OR make sure that you have called report() after making class instance and before calling getValue(); – Abhay Maurya Feb 15 '17 at 13:22
  • @balaraman It sounds like you're expecting the value change to be retained across pages. You should use a session for that if that's the case. Otherwise you have to set the value every time – Machavity Feb 15 '17 at 13:24