我在试着弄清楚$_data vs $this->_data和
class ProductModel
{
var $_data = null; <--- defined here
function test()
{
$this->_data = <--- but it's accessed using $this
}
}我知道在PHP语言中var是用来定义类属性的,但是为什么要用$this来访问它呢?它不应该像$this->$_data一样吗?这里使用的是什么OOP概念?它是特定于PHP的吗?
发布于 2012-11-14 14:44:01
PHP和其他几种流行的编程语言,比如Java (重要的是要注意,PHP的面向对象选择至少部分受到了Java的启发)将上下文中的当前对象实例称为this。您可以将this (或$this in PHP)视为“当前对象实例”。
在类方法内部,$this引用当前的对象实例。
使用上述内容的一个非常小的示例:
$_data = 'some other thing';
public function test() {
$_data = 'something';
echo $_data;
echo $this->_data;
}上面的代码将输出somethingsome other thing。类成员与对象实例一起存储,但局部变量仅在当前范围内定义。
发布于 2012-11-14 14:44:15
不,不应该。因为PHP可以动态地计算成员名称,所以这一行
$this->$_data引用类成员,其名称在局部$data变量中指定。请考虑以下内容:
class ProductModel
{
var $_data = null; <--- defined here
function test()
{
$member = '_data';
$this->$member = <--- here you access $this->_data, not $this->member
}
}发布于 2012-11-14 14:46:59
var $_data定义了一个类变量,$this->_data访问它。
如果设置为$this->$foo,则表示其他含义,就像$$foo一样:如果设置为$foo = 'bar',则这两个表达式的计算结果分别为$this->bar和$bar
https://stackoverflow.com/questions/13374137
复制相似问题