PHP, $this->{$var} — what does that mean?

前端 未结 2 451
温柔的废话
温柔的废话 2020-12-24 07:27

I have encountered the need to access/change a variable as such:

$this->{$var}

The context is with CI datamapper get rules. I cant seem

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 08:19

    This is a variable variable, such that you will end up with $this->{value-of-$val}.

    See: http://php.net/manual/en/language.variables.variable.php

    So for example:

    $this->a = "hello";
    $this->b = "hi";
    $this->val = "howdy";
    
    $val = "a";
    echo $this->{$val}; // outputs "hello"
    
    $val = "b";
    echo $this->{$val}; // outputs "hi"
    
    echo $this->val; // outputs "howdy"
    
    echo $this->{"val"}; // also outputs "howdy"
    

    Working example: http://3v4l.org/QNds9

    This of course is working within a class context. You can use variable variables in a local context just as easily like this:

    $a = "hello";
    $b = "hi";
    
    $val = "a";
    echo $$val; // outputs "hello"
    
    $val = "b";
    echo $$val; // outputs "hi"
    

    Working example: http://3v4l.org/n16sk

提交回复
热议问题