drbe16008 2014-10-03 16:46
浏览 253
已采纳

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

I've been reading up on OO PHP programming and encapsulation and I'm still finding it a little confusing.

I have this code:

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;
    }

}

In my testclass.php file, when I use the set and get Description functions like so:

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

I get an error saying Undefined variable: description. Could someone please explain to me why this is, because I thought the point of a set method was to define the variable? I thought you declare the variable in the class, and then you define the variable when you use the set method so that it can be accessed with the get method?

  • 写回答

2条回答 默认 最新

  • duanfu1942 2014-10-03 16:56
    关注

    Just want to add to the correct answer of @prisoner.

    $this->description
    

    is not the same as

    $this->$description
    

    because this is what you would call a "variable variable".

    For example:

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

    Refer to http://php.net/manual/en/language.variables.variable.php for more details.

    A useful example would be if you would like to access an a variable/function within a given structure.

    Example:

    $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'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)