2014-10-03 29 views
3

我一直在阅读OO 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(); 

我得到一个错误说未定义的变量:描述。有人请向我解释为什么这是因为我认为设置方法的点是来定义变量?我以为你在类中声明了变量,然后在使用set方法时定义变量,以便使用get方法访问该变量?

回答

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' 
4
return $this->$description; 

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

+1

的解释好了感谢,像你这样的建议,我会在这读了!我很快就会得到这个窍门!如@ Reece55建议的 – 2014-10-03 16:53:38

+1

删除额外的$,就像你为构造函数和setDescription函数所做的那样。 – Stv 2014-10-03 16:57:30