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

前端 未结 2 452
温柔的废话
温柔的废话 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:12

    First of all $this->{$var} and $this->var are two very different things. The latter will request the var class variable while the other will request the name of the variable contained in the string of $var. If $var is the string 'foo' then it will request $this->foo and so on.

    This is useful for dynamic programming (when you know the name of the variable only at runtime). But the classic {} notation in a string context is very powerful especially when you have weird variable names:

    ${'y - x'} = 'Ok';
    $var = 'y - x';
    echo ${$var};  
    

    will print Ok even if the variable name y - x isn't valid because of the spaces and the - character.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题