简体   繁体   English

如何从PHP的内部对象获取外部对象用于内部对象的属性名称

[英]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 will use a passed in name for the property name of the class B property. 因此,类B的对象位于类A的内部,并且类A将使用传入的名称作为类B属性的属性名称。 Class B is totally unaware of the name it has been given and really doesn't need to know. B类完全不知道它的名字,真的不需要知道。 But I need to know it in order to access class B from class A. 但是我需要知道它才能从A类访问B类。

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. 我确实对代码有足够的控制权,可以为类B创建一个属性,并将其设置为类A给定的名称。 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 BI just don't know the name it's been given.) 然后,我可以让B类将其名称传递回需要遍历B类的函数(当前它仅返回外部对象,因此我可以访问BI类,只是不知道它的名称而已。)

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. 找出拥有B实例的A成员并不难。 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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM