In JS, when defining an object, if one of the object properties is a function, using the this
keyword within that function will return the current object you are working under. This is useful if you'd like to retrieve the values of other properties within the same object.
For example:
// 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());
However, I can't figure out how to do the equivalent in PHP. I'm running PHP 5.6, so I have access to anonymous functions. Here is my sample code:
<?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']();
?>
EDIT:
As others are pointing out, I "should" be using a real class, and access the classes properties that way.
However, in the code I am working in, I do not have the luxury to making that paradigm change. If there are no alternative options, I'll keep in mind that there isn't an exact one-to-one equivalent for this idea within PHP.