开发者

programmatically defining an array with all class vars

is there a way to create an array cont开发者_如何学Caining 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


Have a look at:

get_class_vars

With this you get the public vars in an array.


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";
}


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";


try get_class_vars($obj);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜