OO PHP基本获取和设置方法"未定义变量"

时间:2014-10-03 16:46:11

标签: php

我一直在阅读有关OO PHP编程和封装的内容,我仍然觉得它有点令人困惑。

我有这段代码:

class Item {

    private $id;
    private $description;

    public function __construct($id) {
        $this->id = $id;
    }

    public function getDescription() {
        return $this->$description;
    }

    public function setDescription($description) {
        $this->description = $description;
    }

}

在我的testclass.php文件中,当我使用set和get这样的函数时:

$item = new Item(1234);
$item->setDescription("Test description");
echo $item->getDescription();

我收到错误说明未定义的变量:description。有人可以向我解释为什么会这样,因为我认为set方法的重点是来定义变量?我以为你在类中声明变量,然后在使用set方法时定义变量,以便可以使用get方法访问它?

2 个答案:

答案 0 :(得分:4)

return $this->$description;

错了。您引用变量$description,而不是返回$this->description。阅读变量变量。

答案 1 :(得分:2)

只想添加@prisoner的正确答案。

$this->description

不同
$this->$description

因为这就是你所谓的"变量"。

例如:

$this->description = "THIS IS A DESCRIPTION!"
$any_variable_name = "description";

echo $this->$any_variable_name; // will echo "THIS IS A DESCRIPTION"
echo $this->description // will echo "THIS IS A DESCRIPTION"
echo $this->$description // will result in an "undefined error" since $description is undefined.

有关详细信息,请参阅http://php.net/manual/en/language.variables.variable.php

一个有用的例子是,如果您想访问给定结构中的变量/函数。

示例:

$url = parseUrl() // returns 'user'

$this->user = 'jim';

$arr = array('jim' => 'the good man', 'bart' => 'the bad man');

echo $arr[$this->$url] // returns 'the good man'
相关问题