类中的php变量variablename

类中的php变量variablename,php,class,variables,dynamically-generated,Php,Class,Variables,Dynamically Generated,谁能告诉我如何在类中使用变量: <?php class test { // set default values; private $type = ''; private $var = array(); public function __construct() { // add element to array $this->var[] = 'abc';

谁能告诉我如何在类中使用变量:

    <?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
应该是动态的,并返回其名称的“value”,在本例中,这是“var”的值,它是一个值为“
数组(…)
”的变量

这应该适合您:

type
也是类属性,因此必须使用
$this

输出:

Array ( [0] => abc )
编辑:


您可以在这里阅读更多关于我在手册中使用
{}
的原因:

当您访问在类的任何函数中定义的变量时 这样做:

$this->variable\u name

没有$

不是这样的

$this->$variable_name

在调用这些方法bar(),foo()的地方,我当然可以在方法范围内设置临时变量,但在全局范围内没有这个“迂回”是否可能。我编辑过。你的代码中没有类测试的右括号。在
$this->{$this->type}中使用
{
}
的目的是什么?我经常看到它们被使用,但我不知道为什么。感谢这些信息,我还不知道
{$var}
@安德烈。那么因为各种原因:1。由于我们对变量使用类属性,它会尝试这样做:
$this->$this
,因此它会尝试将对象转换为它想要访问的字符串,但这不起作用,这是第一个也是主要原因2。如果OP想要访问一个特定的数组元素,那么他可以把
[X]
放在后面。(否则,像:
$$a[1]
这样的事情会出现问题)3。为了可读性,我喜欢this@Rizier123啊,我现在明白了。我实际上不经常使用变量(请阅读:从不)。对发生的事情有点困惑。感谢您的解释。我添加了
$
以访问名为
variable\u name
的变量值。我不知道
{$var}
解决方案。
$this->$variable_name