Search code examples
phpclass-variables

PHP - Set class variable from another class variable within same class?


I'm trying to set up a PHP class:

class SomeClass {
    private $tags = array(
        'gen1' => array('some string', 1), 
        'gen2' => array('some string', 2), 
        'gen3' => array('some string', 3), 
        'gen4' => array('some string', 4), 
        'gen5' => array('some string', 5), 
    );

    private $otherVar = $tags['gen1'][0];
}

But this throws the error:

PHP Parse error: syntax error, unexpected '$tags'

Switching it to the usual...

private $otherVar = $this->tags['gen1'][0];

returns the same error:

PHP Parse error: syntax error, unexpected '$this'

But accessing the variable within a function is fine:

private $otherVar;

public function someFunct() {
    $this->otherVar = $this->tags['gen1'][0];
}

How can I use the previously defined class variable to define and initialize the current one, without an additional function?


Solution

  • The closest way to do what you desire is to put the assignment in the constructor. For example:

    class SomeClass {
        private $tags = array(
            'gen1' => array('some string', 1), 
            'gen2' => array('some string', 2), 
            'gen3' => array('some string', 3), 
            'gen4' => array('some string', 4), 
            'gen5' => array('some string', 5), 
        );
    
        private $otherVar;
    
        function __construct() {
             $this->otherVar = $this->tags['gen1'][0];
        }
    
        function getOtherVar() {
            return $this->otherVar;
        }
    }
    
    $sc = new SomeClass();
    echo $s->getOtherVar(); // echoes some string