calling a private array from another private array in php
I don't understand why doesn't this code work:
<?php
class Test {
private $BIG = array(
'a' => 'A',
'b' => 'B',
'c' => 'C'
);
开发者_高级运维 private $arr2 = array(
$this->BIG['a'],
$this->BIG['b'],
'something'
);
public function getArr2(){
return $this->arr2;
}
}
$t = new Test();
print_r($t->getArr2());
?>
I get this error:
Parse error: syntax error, unexpected T_VARIABLE, expecting ')' in /home/web/te/test.php on line 11
You can't combine variables in a class member definition. You can only use native types and constants:
private $arr = array('a', 'b');
private $obj = new stdClass(); // error
private $obj = (object)array(); // error
private $num = 4;
private $a = 1;
private $b = 2;
private $c = $this->a + .... // error
If you want to combine or calculate, do that in __construct
:
private $a = 1;
private $b = 2;
private $c;
function __construct() {
$this->c = $this->a + $this->b;
}
You can't reference $this when declaring properties.
From the PHP Documentation:
[Property] declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Therefore, do actions like that in the constructor:
class Test {
private $BIG = array(
'a' => 'A',
'b' => 'B',
'c' => 'C'
);
private $arr2;
public function __construct()
{
$this->arr2 = array(
$this->BIG['a'],
$this->BIG['b'],
'something'
);
}
public function getArr2(){
return $this->arr2;
}
}
精彩评论