How to get the property name used by outer-object for inner-object from the inner-object in PHP
Okay, so code which is outside my control works like this:
Class A {
function use_b($b_name) {
$this -> $b_name = new B();
}
}
Class B {
var $stuff;
}
So that the object of class B is inside of class A and class A wi开发者_如何学运维ll use a passed in name for the property name of the class B property. Class B is totally unaware of the name it has been given and really doesn't need to know. But I need to know it in order to access class B from class A.
I do have enough control over the code that I can create a property for class B and set it to the name class A has given it, if that is possible. Then I can have class B pass it's name back to my function that needs to traverse class B (currently it returns only the outer object, so I have access to class B I just don't know the name it's been given.)
If that made no sense at all, please comment and let me know.
Finding out the members of A that hold instances of B is not that hard. Try this code:
<?php
Class A {
function use_b($b_name) {
$this -> $b_name = new B();
}
}
Class B {
var $stuff;
}
$a = new A();
$a->use_b('test');
foreach(get_object_vars($a) as $key=>$val)
if(get_class($val) == 'B')
echo $key . " is the member that holds an instance of B";
精彩评论