检查属性在PHP中属于哪个类

时间:2015-01-04 18:29:45

标签: php

好吧,让我们说我有一个名为test的字符串,我知道这个字符串实际上是在我的一个类中用作属性名。有没有办法找出哪个类的名称为test

这样的事情可能是:

class Foobar {
    private $foo;
}

class Bazbar {
    private $test;
}

$attr_name = 'test';
echo get_class_name_by_attr($attr_name); // Would output Bazbar

快速即兴创作此代码......

有没有办法在PHP中实现这一点?

2 个答案:

答案 0 :(得分:3)

我同意那些认为你必须重新分析问题的人。但问题的答案是这样的:

foreach (get_declared_classes() as $class) {
    if (property_exists($class, 'test')) {
        echo $class. " has the propriety test.\n"; 
    }
}

答案 1 :(得分:0)

这应该适合你:

(我仍然问自己为什么需要这个,但我希望这有帮助)

<?php

    class Foobar {
        private $foo;
    }

    class Bazbar {
        private $test;
    }


    $attr_name = "test";
    $check_classes = array("Foobar", "Bazbar");

    foreach($check_classes as $k => $v) {
        $obj = new $v();
        $obj = new ReflectionClass($obj);
        $classes[]   = $obj->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE);
    }

    foreach($classes as $class) {
        foreach($class as $prop) {

            if($prop->getName() == $attr_name)
                echo "Class: " . $class[0]->class. " Prop: " . $prop->getName();

        }
    }

?>

输出:

Class: Bazbar Prop: test

这里我添加了一个数组,在这些类中搜索形成attr。名称。为此,我使用反射。你可以在这里阅读:http://uk.php.net/manual/en/book.reflection.php

相关问题