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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么