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)
CodePudding user response:
I think you should make a better case for why you would want to do this. That said, the Closure::bind()
is indeed a bit tedious. There is something you can do, but I doubt you will like it. It goes like this:
$human = (object) [
'name' => 'John Doe',
'age' => 25,
'getName' => function($object) {
var_dump($object->name);
},
'getAge' => function($object) {
var_dump($object->age);
},
];
($human->getName)($human);
($human->getAge)($human);
See: PHP fiddle
Here you admit that, at the time of creation, the functions aren't aware that they are part of an object, when $this
would make sense. Therefore you supply the needed object later as an argument, and everything is fine.
Again, creating a normal class would be preferable, if only because it is easier to understand. Remember, you write code to do something, but also because it is a way to communicate your intent to yourself and others.
I thought of another way to do this. Also not what you want, but it kind of works:
$human = (object) [
'name' => 'John Doe',
'age' => 25,
'getName' => function() {
global $human;
var_dump($human->name);
},
'getAge' => function() {
global $human;
var_dump($human->age);
},
];
($human->getName)();
($human->getAge)();
See: PHP fiddle
CodePudding user response:
mayby
$human = (object) [
'name' => 'John Doe',
'age' => 25,
];
print_r($human->name);
print_r($human->age);