当我在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() {
}
}
在浏览器中访问该类时会抛出错误:
解析错误:第7行的C:\ xampp \ htdocs \ dev.virtualnerd.com_classes \ setup.class.php中的语法错误,意外'(',期待','或';'
第7行为private $acctsInList = count($this->acctListArr);
你能否以这种方式定义私有变量?
答案 0 :(得分:11)
来自the docs:
此声明可能包括初始化,但此初始化必须是常量值 - 也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估。
正如其他人所指出的那样,你可以改为进行计算并在构造函数中指定它。
答案 1 :(得分: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);
}
答案 2 :(得分:0)
你想要的是
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 = 0;
public function __construct() {
$this->acctsInList = count($this->acctListArr);
}
}
答案 3 :(得分:0)
您可以像这样编写类
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 = 0;
public function __construct() {
$this->acctsInList = count($this->acctListArr);
}
}