在私有类成员定义中使用count()会导致Parse错误

bre*_*rer 0 php variables class

当我在php类中定义私有变量时使用count时,它会抛出一个错误.这是我的课

class setup {

private $acctListArr = array(4533,4534,4535,4536,4537,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4550,4551,4552,4553,4554,4555,4556,4557,4559,4560,4561,4562,4563,4564,4565,4566,4567,4568,4569,4570,4571,4572,4573,4574,4575,45766,4577,4578,4579,4580,4581,4582,4583,4584,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611,4612,4613,4614,4615,4616,4617,4618);
private $acctsInList = count($this->acctListArr);

public function __construct() {
}

}
Run Code Online (Sandbox Code Playgroud)

在浏览器中访问该类时会抛出错误:

解析错误:第7行的C:\ xampp\htdocs\dev.virtualnerd.com_classes\setup.class.php中的语法错误,意外'(',期待','或';')

第7行是 private $acctsInList = count($this->acctListArr);

你不能用这种方式定义私有变量吗?

Wis*_*guy 11

不,你不能.无法使用计算值(例如,函数调用)定义类属性.

来自文档:

此声明可能包括初始化,但此初始化必须是常量值 - 也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估.

正如其他人所指出的那样,您可以改为进行计算并在构造函数中进行分配.


Wes*_*row 5

您不能在实例变量的声明中调用函数.而是在构造函数中指定它,如下所示:

 private $acctListArr = array(4533,4534,4535,4536,4537,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4550,4551,4552,4553,4554,4555,4556,4557,4559,4560,4561,4562,4563,4564,4565,4566,4567,4568,4569,4570,4571,4572,4573,4574,4575,45766,4577,4578,4579,4580,4581,4582,4583,4584,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611,4612,4613,4614,4615,4616,4617,4618);

 private $acctsInList;

 public function __construct() {
     $this->acctsInList = count($this->acctListArr);
 }
Run Code Online (Sandbox Code Playgroud)