简体   繁体   中英

Global variable inside class and function PHP

I'm having trouble with reading variable defined in one function in another function. I have:

global $a;
class test{
    function aa($somevar){
        switch ($myvar){
        case 'value':
            global $a;
            $a = 15;
            break;
        }
    }
    function bb(){
        global $a;
        echo $a;
    }
}

$foo = new test();
$ccc = $foo->bb();

var_dump($ccc);

I get dump result NULL. Thanx

变量$a应该是类内的一个属性

At no point in your code do you assign a value to $a .

The only assignment to $a is in the test->aa method, which uses inconsistent variables and therefore even if called will never assign to $a .

You never run test->aa() to assign a value to a .

$foo = new test();
$foo->aa();
$ccc = $foo->bb();

In this case $ccc will still be null because you are echoing $a in $foo->bb() instead of returning it.

function bb() {
  global $a;
  return $a;
}

I would also stay away from globals and pass the variable $a on construct of the class. For example:

class test {
    public $a;

    function __construct($a = null) {
      // pass initial var to $a if you want
      $this->a = $a;
    }

   function aa($somevar) {
      // reassign $a
      $this->a = $somevar;
   }
}

$foo = new test();
$foo->aa(5);
// or just $foo = new test(5);
var_dump($foo->a);

Try this :

class test
{
    public $a;
    function aa($somevar)
    {
        switch ($myvar)
        {
         case 'value':
         $this->a = 15;
         break;
        }
    }
    function bb()
    {        
        return $this->a;
    }
}

$foo = new test();
$ccc = $foo->bb();

var_dump($ccc);

UPDATED:

<?php
class test
{
    var $a;
    function aa($somevar)
    {
        switch ($somevar)
        {
         case 'value':
         $this->a = 15;
         break;
        }
    }
    function bb()
    {        
        return $this->a;
    }
}

$foo = new test();
$foo->aa('value');
$ccc = $foo->bb();

var_dump($ccc);
?>

Here is code try this..

<?php
 global $a;
  class test{

    function aa($somevar){
       switch ($somevar){
        case 'value':
            global $a;
            $a = 15;
            break;
        }
    }

function bb(){
    global $a;
    echo $a;
    return $a;
}
}

$foo = new test();
$foo->aa('value');
$ccc = $foo->bb();

var_dump($ccc);


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM