is there way for programmatically storing an 'address' of properties for an objects in PHP?
Suppose I have an o开发者_StackOverflowbject in PHP $o, about which I can get $o->a->b, or maybe $0->c['d'].
Is there a way of storing these as sort of address for handling elsewhere?
What I have is that at several different places I need to process different properties of the object, but in the same way.
So what I'd like to do is build a collection of addresses as I go along, and then hand them all to a single function which goes through them all and does the processing.
Eg:
$o->a = 'red';
$o->b->c = 'red';
$o->d['e'] = 'red';
... and I want to change all 'red' to 'green', but those particular keys and properties may change depending on circumstances.
You can do this:
$propertyName = 'a';
$o->$propertyName = 'green';
But not this:
$propertyName = 'b->c';
$o->$propertyName = 'green';
Alternatively, you can create references to the variables, like this:
$a[] = & $o->a;
$a[] = & $o->b->c;
$a[] = & $o->d['e'];
foreach ($a as $key => $color) {
$a[$key] = 'green';
}
Per Manual: Variable variables:
<?php
class foo {
var $bar = 'I am bar.';
}
$foo = new foo();
$f = 'foo';
$b = 'bar';
echo $$f->$b;
So you could make a chain with property names:
<?php
class CB { var $c = 'whee'; }
class CO { var $b; }
$o = new CO();
$o->b = new CB();
// normal access
echo $o->b->c;
// variable access
$chain = array( 'o', 'b', 'c' ); // for $o->b->c
$obj = ${ array_shift( $chain ) };
while ( sizeof( $chain ) > 1 ) {
$obj = $obj->{ array_shift( $chain ) };
}
echo $obj->{ $chain[0] };
A little advice...
Public properties of any object can cause you all manner of problems. It may be that what ever you are doing really does require it but I would suggest you use getters and setters in your class and call these properties elsewhere.
You then control what can be changed and how it can be changed.
精彩评论