php class 中的变量变量名

php variable variablename in class

谁能告诉我如何在 类:

中使用可变变量
    <?php

    class test
    {
        // set default values;
        private $type = '';
        private $var = array();

    public function __construct()
    {
        // add element to array
        $this->var[] = 'abc';

        // set $type to make it dynamically accessible
        $this->type = 'var';
    }

    public function bar()
    {
        // return variable $var;
        return $this->$type; // should give array([0]=>'abc') BUT give 'Undefined variable: type'  and 'Cannot access empty property';
    }
}                                                                                      
    $class = new test;
    var_dump($class->bar());
    ?>  

所以$this->type应该是动态的,return是它名字的"value",在这个例子中就是'var'的值,这是一个有值的变量'array(...)'。

这应该适合你:

(type 也是一个 class 属性 所以你必须使用 $this)

return $this->{$this->type}; 

输出:

Array ( [0] => abc )

编辑:

您可以在此处的手册中详细了解我使用 {} 的原因:http://php.net/manual/en/language.variables.variable.php

当您访问 class 的任何函数内定义的变量时 这样做:

$this->variable_name

没有$

不是这样的

$this->$variable_name