检查 class 属性属于 PHP
Check to which class a property belongs in PHP
好吧,假设我有一个名为 test
的字符串,我知道这个字符串实际上用作我的 classes 之一的属性名称。有没有办法找出哪个 class 有一个名为 test
的名字?
可能是这样的:
class Foobar {
private $foo;
}
class Bazbar {
private $test;
}
$attr_name = 'test';
echo get_class_name_by_attr($attr_name); // Would output Bazbar
快速即兴创作这段代码...
有没有办法在 PHP 中实现这一点?
这应该适合你:
(我还在问自己为什么需要这个,但我希望这有帮助)
<?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
我同意那些认为您必须重新分析问题的人。但是问题的答案是这样的:
foreach (get_declared_classes() as $class) {
if (property_exists($class, 'test')) {
echo $class. " has the propriety test.\n";
}
}
好吧,假设我有一个名为 test
的字符串,我知道这个字符串实际上用作我的 classes 之一的属性名称。有没有办法找出哪个 class 有一个名为 test
的名字?
可能是这样的:
class Foobar {
private $foo;
}
class Bazbar {
private $test;
}
$attr_name = 'test';
echo get_class_name_by_attr($attr_name); // Would output Bazbar
快速即兴创作这段代码...
有没有办法在 PHP 中实现这一点?
这应该适合你:
(我还在问自己为什么需要这个,但我希望这有帮助)
<?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
我同意那些认为您必须重新分析问题的人。但是问题的答案是这样的:
foreach (get_declared_classes() as $class) {
if (property_exists($class, 'test')) {
echo $class. " has the propriety test.\n";
}
}