开发者

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(); // shou开发者_如何学编程ld be 5

Is it possible


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


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';


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.


You can use static variables:

class AAA{
  public static $var = 0;

  function getvar() {
    return AAA::$var;
  }

}

AAA::$var = "test";

$a1 = new AAA();
var_dump($a1->getvar());
var_dump(AAA::$var);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜