Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared variable across multiple class instances that I can change outside the class

the code explains it better:

class Class{
  $var = 0;

  function getvar()
    echo $this->var;
  }

}



$inst1 = new Class();

// I want to change $var here to 5

$inst2 = new Class();

echo $inst2->getvar(); // should be 5

Is it possible

like image 700
pulă Avatar asked Jul 04 '11 20:07

pulă


3 Answers

Static. http://php.net/manual/en/language.oop5.static.php

class MyClass {
    public static $var = 0;

    function setVar($value) {
        self::$var = $value;
    }

    function getVar() {
        return self::$var;
    }
}

echo MyClass::$var;
MyClass::setVar(1);
echo MyClass::getVar();  //Outputs 1
like image 119
Jack Murdoch Avatar answered Nov 15 '22 13:11

Jack Murdoch


You should be able to do this using a static member variable.

class foo {
  private static $var;

  public static setVar($value) {
    self::$var = $value;
  }

  public static getVar() {
    return self::$var;
  }
}

$a = new foo;
$a::setVar('bar');

$b = new foo;
echo $b::getVar();
// should echo 'bar';
like image 26
thetaiko Avatar answered Nov 15 '22 14:11

thetaiko


You should declare $var to be static:

A data member that is commonly available to all objects of a class is called a static member. Unlike regular data members, static members share the memory space between all objects of the same class.

like image 21
Igor Avatar answered Nov 15 '22 12:11

Igor