I used to get all public vars from a class inside a class with a Closure like this:
Class myClass
{
public $foo;
private $bar;
private function GetFields()
{
$lambda = function( $obj ) { return get_object_vars( $obj ); };
return $lambda( $this );
}
public function SomeFunction()
{
$fields = $this->GetFields();
}
}
This worked perfect, and gave me all public vars while inside a class.
Now, I upgraded my server to PHP 5.4 and I get all privates and protected vars to. Is that a new 'Feature' or is it a Bug?
To answer my own question, its a unwanted side effect of moving closures into the scope of the class.
Have a look at: https://wiki.php.net/rfc/closures/object-extension
In the end I thinks its a bug or at least a unwanted 'Feature'.
I'll must think another strategy to find all public properties of a class, while inside a class.
update:
this is what I came up with:
Class myClass
{
public $foo;
private $bar;
private function GetFields()
{
$fields = [];
$ref = (new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ( $ref as $value )
$fields[$value->name] = $this->{$value->name};
return $fields;
}
public function SomeFunction()
{
$fields = $this->GetFields();
}
}
From the docs for get_object_vars()
.
Returns an associative array of defined object accessible non-static properties for the specified object in scope.
I'm assuming, when you are using the $this
context get_object_vars()
is giving you all the accessible properties. Which would include private
and protected
.
In PHP 5.4 you can now use $this
inside anonymous functions. Scroll down and look at the changelog. http://php.net/manual/en/functions.anonymous.php
Changelog
5.4.0 | $this can be used in anonymous functions
Look at the use case of this function in the manual: http://php.net/manual/en/function.get-object-vars.php
You have to cases there, the first one when you are creating an instance on an object and the second one inside a class. Those two cases have different results. The first one shows only public attributes, the second one shows all attributes.
The difference comes from the fact that get_object_vars()
returns all accessible properties of an object. When you are creating an instance of an object and passing it as a parameter to the function it can access only public attributes but when you are inside of the class and you are passing $this
as a parameter it can access all attributes.