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

前端 未结 2 473
温柔的废话
温柔的废话 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.

提交回复
热议问题