I bound the $this variable with Closure::bind() method (lines 12-13) to my getName() and getAge() methods (lines 4 and 7) so that they can refer to their own member fields (lines 2-3) in an instance of stdClass. It works, but I find this a bit tedious.
Is there any special variable or built-in function that I can refer to the current instance of stdClass inside my getName() and getAge() methods (lines 4 and 7) without calling Closure::bind() method? Or, is there any workaround to this, if any?
PHP Code
$human = (object) [
'name' => 'John Doe',
'age' => 25,
'getName' => function() {
var_dump($this->name);
},
'getAge' => function() {
var_dump($this->age);
},
];
$human->getName = Closure::bind($human->getName, $human);
$human->getAge = Closure::bind($human->getAge, $human);
print_r($human);
($human->getName)();
($human->getAge)();
Sample Output:
stdClass Object
(
[name] => John Doe
[age] => 25
[getName] => Closure Object
(
[this] => stdClass Object
*RECURSION*
)
[getAge] => Closure Object
(
[this] => stdClass Object
*RECURSION*
)
)
string(8) "John Doe"
int(25)