duankuaizhe8257 2016-10-06 01:30
浏览 76
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • duangenshi9836 2016-10-06 01:50
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向