Reputation: 30731
is there a way to create an array containing all the public vars from a class without having to add them manually in PHP5?
I am looking for the quickest way to sequentially set a group of vars in a class
Upvotes: 2
Views: 247
Reputation: 27102
get_class_vars()
is the obvious one - see get_class_vars docs on the PHP site.
Edit: example of setting using this function:
$foo = new Foo();
$properties = get_class_vars("Foo");
foreach ($vars as $property)
{
$foo->{$property} = "some value";
}
You could also use the Reflection API - from the PHP docs:
<?php
class Foo {
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}
$foo = new Foo();
$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $prop) {
print $prop->getName() . "\n";
}
var_dump($props);
?>
...example taken straight from the PHP docs linked above but tweaked for your purpose to only retrieve public properties. You can filter on public, protected etc as required.
This returns an array of ReflectionProperty
objects which contain the name and class as appropriate.
Edit: example of setting using the above $props
array:
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $prop)
{
$foo->{$prop->getName()} = "some value";
}
Upvotes: 3
Reputation: 44346
Take a look at PHP's Reflection API. You can get the properties with ReflectionClass::getProperties.
To set the properties you do something like this:
$propToSet = 'somePropName';
$obj->{$propToSet} = "newValue";
Upvotes: 1