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


OO PHP basic get and set methods "Undefined variable"

我一直在阅读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并获得Description函数时,如下所示:

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

我得到一个错误说未定义的变量:描述。有人能向我解释为什么会这样吗,因为我认为集合方法的要点是来定义变量吗?我想您在类中声明变量,然后在使用set方法时定义变量,以便可以使用get方法访问它?

return $this->$description;

是错误的。您引用的是变量$description,而不是返回$this->description。读取变量。

只想添加到@caption的正确答案中。

$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'