我试图声明变量如下:
class GumballMachine {
private static $SOLD_OUT = 0;
private $state = $SOLD_OUT;
private function GumballMachine (){}
}
如何将 $SOLD_OUT 的值分配给 $state 或有其他方法吗?
您可以使用类常量执行此操作
const SOLD_OUT = 0;
private $state = self::SOLD_OUT;
您需要使用一个常量值。此外,您需要将您的构造函数声明为公共的,否则您将遇到错误。
class GumballMachine {
const SOLD_OUT = 0;
private $state = self::SOLD_OUT;
public function GumballMachine () { }
}
`class GumballMachine {
private static $SOLD_OUT = 0;
private $state = 0;
private function GumballMachine ()
{
$this->state=$SOLD_OUT;
}
}`