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条)

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿