Is there a quick way to tell if the property of a class is dynamic?
Consider the following code:
class Foo {
public $bar;
}
$obj = new Foo;
$obj->baz = 1;
How can I tell that $bar
is declared and $baz
is dynamic?
CodePudding user response:
You can do this in two parts, first get the class variables from $obj
and then the object variables
$static = get_class_vars(get_class($obj));
$all = get_object_vars($obj);
(using get_class()
allows you to make it based on any object as it fetches the class of the object rather than hard coding it)
Then the difference between the two are the dynamic variables...
$dynamic = array_diff_key($all, $static);
So for your example...
print_r($static);
print_r($dynamic);
gives
Array
(
[bar] =>
)
Array
(
[baz] => 1
)
CodePudding user response:
Here is an implementation of function is_dynamic():
function is_dynamic($object, $property_name)
{
return array_key_exists($property_name, get_object_vars($object)) &&
!array_key_exists($property_name, get_class_vars(get_class($object)));
}