Reputation: 4531
Okay, let's say I have a string named test
and I know that this string is actually used as a property name in one of my classes. Is there a way to find out which class has a name with the name test
?
Something like this maybe:
class Foobar {
private $foo;
}
class Bazbar {
private $test;
}
$attr_name = 'test';
echo get_class_name_by_attr($attr_name); // Would output Bazbar
Quickly improvised this code...
Is there a way to achieve this in PHP?
Upvotes: 0
Views: 76
Reputation: 36964
I agree with those people who think that you have to re-analyze your problem. But the answer of the question is something like this:
foreach (get_declared_classes() as $class) {
if (property_exists($class, 'test')) {
echo $class. " has the propriety test.\n";
}
}
Upvotes: 3
Reputation: 59701
This should work for you:
(I'm still asking myself why you need this, but i hope this helps)
<?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();
}
}
?>
Output:
Class: Bazbar Prop: test
Here i added an array which search in these classes form the attr. name. For this i use Reflection. You can read up on this here: http://uk.php.net/manual/en/book.reflection.php
Upvotes: 0