duanlu0386 2012-11-14 06:39
浏览 97
已采纳

$ _data vs $ this - > _ data - PHP

I'm trying to figure out the difference between $_data vs $this->_data

class ProductModel
{

    var $_data = null; <--- defined here

    function test() 
    {
       $this->_data = <--- but it's accessed using $this
    }

}

I know in PHP var is used to define class properties but Why is it accessed using $this. Shouldn't it be like $this->$_data ? What's OOP concept is being used here ? Is it a PHP specific?

  • 写回答

3条回答 默认 最新

  • dsen53898 2012-11-14 06:44
    关注

    PHP along with several other popular programming languages such as Java (it's important to note that PHP's Object Oriented choices were at least partially inspired by Java) refer to the current object instance in context as this. You can think of this, (or $this in PHP) as the "current object instance."

    Inside of class methods, $this refers to the current object instance.

    A very small example using what you have above:

    $_data = 'some other thing';
    public function test() {
       $_data = 'something';
       echo $_data;
       echo $this->_data;
    }
    

    The above will output somethingsome other thing. Class members are stored along with the object instance, but local variables are only defined within the current scope.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大