在JS中,在定义对象时,如果对象属性之一是函数,则在该函数中使用this
关键字将返回您正在使用的当前对象。如果要检索同一对象中其他属性的值,这将非常有用。
例如:
// Javascript Code
var val = 'I never get seen.';
var o = {
val: 'I do get seen!',
fun: function() {
// use `this` to reference the current object we are in!
return this.val;
}
};
// Outputs 'I do get seen!'
console.log(o.fun());
但是,我不知道如何在 PHP 中执行等效操作。我运行的是 PHP 5.6,所以我可以访问匿名函数。这是我的示例代码:
<?php
// PHP Code
$val = 'I never get seen.';
$o = array(
'val' => 'I do get seen!',
'fun' => function() {
/**
* I've tried:
*
* return $this.val;
* return $this->val;
* return $this['val'];
* return this.val;
* return this->val;
* return this['val'];
*
* None of them work.
*/
return $this->val;
}
);
// Should output 'I do get seen!'
echo $o['fun']();
?>
编辑:
正如其他人指出的那样,我"应该"使用一个真正的类,并以这种方式访问类属性。
但是,在我正在编写的代码中,我没有奢侈地进行这种范式更改。如果没有其他选择,我会记住,在 PHP 中没有一个确切的一对一等价物。
如何在 PHP 中定义一个类:
class test {
private $val = "value";
function fun() {
return $this->val();
}
}
//instantiation:
$obj = new test();
echo $obj->fun();
PHP 是一种实际上支持类的语言,并且不必通过对所有内容使用数组来欺骗
重要的是要注意,你不能只使用一种语言(JS)中的所有东西,并将其"转换"为其他语言(PHP)。您实际上可以通过使用匿名类来接近:
<?php
$o = new class {
public $val = 'I do get seen!';
public function fun() {
// use `this` to reference the current object we are in!
return $this->val;
}
};
var_dump($o->fun());
是否应该这样做...我对此非常怀疑。
不同的语言(特别是基于原型和基于经典OOP的语言)只是做事不同。