简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM