I’ve got a class Foo with public and protected properties. Foo needs to have a non-static method, getPublicVars() that returns a list of all the public properties of Foo (this is just an example, I know from outside the Foo object calling get_object_vars() will accomplish this and there is no need for my getPublicVars() method).
Note: This must also return dynamically declared properties assigned at runtime to the class instance (object) that aren’t defined in the class’s definition.
Here’s the example:
class Foo{
private $bar = '123';
protect $boo = '456';
public $beer = 'yum';
//will return an array or comma seperated list
public function getPublicVars(){
// thar' be magic here...
}
}
$foo = new Foo();
$foo->tricky = 'dynamically added var';
$result = $foo->getPublicVars();
var_dump($result); // array or comma list with 'tricky' and 'beer'
What is the most concise way to get the only the public properties of an object from inside a class’s own methods where both public and protected are visible?
I’ve looked at:
But this doesn’t seem to address my question as it points to using get_object_vars() from outside the object.
Since PHP 8.1 (Nov 2021) first class callable syntax is available to create the closure, then __invoke() it:
Since PHP 7.1 (Dec 2016) creating a closure from a callable is available to create the closure, then __invoke() it:
Since PHP 7.0 (Dec 2015) a closure can be created, bound out of scope:
(ikkez has a PHP 7.4 variation of it in their answer back in 2022.)
Before PHP 7.0, the implementation-specified behaviour of call_user_func() could be used, this is Brad Kents’ example:
As you already realized, PHP’s build in
get_object_varsis scope-sensitive. You want the public object properties only.So from that function to the public variant is not a large step:
Calling this
get_object_public_varswill give you only the public properties then because it is a place out of scope for the current $object.If you need more fine-grained control, you can also make use of the
ReflectionObject:Which has the benefit that you don’t need to introduce another function in the global namespace.
The function create_user_func() shouldn’t be used (because eval() and IIRC each time a new function was created). Luckily, since PHP 5.3 (Jun 2009) there are anonymous functions.
However, it is a correct answer to the question given when jumc answered in Apr 2013 Brad Kents’ hack was not there yet and no other answer existed to show changing the scope of the closure that requires PHP 5.4 (Mar 2012; "Implemented closure rebinding as parameter to bindTo." ref).
Therefore, for completeness, the PHP 5.4 syntax closure example:
as the alternative form of: