1

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

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can't reference $this when declaring properties.

Comments

1

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.