跨多个类实例的共享变量,我可以在类外部进行更改

pul*_*ulă 9 php oop variables class

代码解释得更好:

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
Run Code Online (Sandbox Code Playgroud)

可能吗

Jac*_*och 17

静态的.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
Run Code Online (Sandbox Code Playgroud)


the*_*iko 6

您应该能够使用静态成员变量执行此操作.

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';
Run Code Online (Sandbox Code Playgroud)