2

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

hakre
  • 193,403
  • 52
  • 435
  • 836
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • Related: [How to programatically find public properties of a class from inside one of it's methods](http://stackoverflow.com/q/13124072/367456) – hakre Oct 29 '12 at 17:06

4 Answers4

5

Have a look at:

get_class_vars

With this you get the public vars in an array.

enricog
  • 4,226
  • 5
  • 35
  • 54
3

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";
}
Josh
  • 10,961
  • 11
  • 65
  • 108
richsage
  • 26,912
  • 8
  • 58
  • 65
1

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";
Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
0

try get_class_vars($obj);

Petah
  • 45,477
  • 28
  • 157
  • 213