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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化