【问题标题】:PHP - Set class variable from another class variable within same class?PHP - 从同一类中的另一个类变量设置类变量?
【发布时间】:2017-02-14 14:47:15
【问题描述】:

我正在尝试设置一个 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];
}

但这会引发错误:

PHP 解析错误:语法错误,意外的“$tags”

将其切换到通常的...

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

返回相同的错误:

PHP 解析错误:语法错误,意外的 '$this'

但是在函数中访问变量很好:

private $otherVar;

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

如何使用之前定义的类变量来定义和初始化当前的类变量,而不需要额外的函数?

【问题讨论】:

标签: php class-variables


【解决方案1】:

做你想做的最接近的方法是将赋值放在构造函数中。例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-21
    • 2015-06-09
    • 2022-09-24
    • 1970-01-01
    • 2023-04-07
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多