简体   繁体   English

PHP - 从同一个类中的另一个类变量设置类变量?

[英]PHP - Set class variable from another class variable within same class?

I'm trying to set up a PHP class: 我正在尝试建立一个PHP类:

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' PHP解析错误:语法错误,意外'$ tags'

Switching it to the usual... 将它切换到通常......

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

returns the same error: 返回相同的错误:

PHP Parse error: syntax error, unexpected '$this' PHP Parse错误:语法错误,意外'$ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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