note 126846 deleted from closure.bindto by cmb
| From: | cmb@php.net | Date: | Sun, 13 Feb 2022 09:39:09 +0000 |
| Subject: | note 126846 deleted from closure.bindto by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217615@lists.php.net to get a copy of this message | ||
Note Submitter: Olexandr Kalaidzhy
----
Get all object vars without using Reflection:
<?php
declare(strict_types=1);
class A
{
private $foo = 'foo';
protected $bar = 'bar';
public $buz = 'buz';
}
function get_object_vars_all($object): array
{
if (!\is_object($object)) {
throw new \InvalidArgumentException(sprintf('The argument should be an object,
"%s" given.', get_debug_type($object)));
}
$closure = function () {
return get_object_vars($this);
};
return $closure->bindTo($object, $object)();
}
$a = new A();
var_dump(get_object_vars($a));
var_dump(get_object_vars_all($a));
?>
The output:
array(1) {
["buz"]=>
string(3) "buz"
}
array(3) {
["foo"]=>
string(3) "foo"
["bar"]=>
string(3) "bar"
["buz"]=>
string(3) "buz"
}