在 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 是一种实际上支持类的语言,不必通过使用数组来处理所有事情
关于javascript - PHP 相当于 JavaScript "this"关键字,特别是在对象内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35321551/