我需要使用PHP 反射 API来获取非 static类的所有可公开访问的属性。
为了只获取非静态的公共属性,我能看到的唯一方法是获取 IS_STATIC 属性并用于array_diff()仅获取公共属性。
最后的课程是这样的:
class foo {
public static $a;
public static $b;
public static $c;
public $d;
public $e;
public $f;
public function reflect()
{
$reflection = new ReflectionClass($this);
$public = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$static = $reflection->getProperties(ReflectionProperty::IS_STATIC);
$properties = array_diff($public, $static);
foreach($properties as $property) {
echo $property->name . "n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
称呼:
$foo = new foo;
$foo->reflect();
Run Code Online (Sandbox Code Playgroud)
reflect()现在的输出如下所示:
d
e
f
Run Code Online (Sandbox Code Playgroud)
问题:有没有更好的方法来做到这一点?
注意:我原来的班级太长了!这个类是一个类似于我的例子。
首先,我发布了另一个关于此的问题,但没有得到答案,所以我需要发布一个新问题。
我有一个按层次列出类别的函数,我用foreach循环创建了另一个函数(在同一个函数上),并将其用于下拉列表,所以不需要创建另一个查询,多次使用我现有的函数。
我想使用相同的查询来列出所选类别下的子类别。
示例:如果category.php?id=100单击,那么我想在登录页面中列出 100 层级下的子类别。
这是我的功能:
$allCategories = array();
$categoryMulti = array(
'categories' => array(),
'parent_cats' => array()
);
while ($row = $stmt->fetch()) {
//I created another array to get subcats didnt work
//$categories['categories'][1]
$categoryMulti['categories'][$row['cat_id']] = $row;
$categoryMulti['parent_cats'][$row['parent_id']][] = $row['cat_id'];
$allCategories[] = $row;
}
function listCategoryTree($parent, $category)
{
$html = "";
if (isset($category['parent_cats'][$parent])) {
$html .= "<ul>\n";
foreach
($category['parent_cats'][$parent] as $cat_id) {
if (!isset($category['parent_cats'][$cat_id])) {
$html .= "<li>" . $category['categories'][$cat_id]['cat_name'] . "</li>";
} else { …Run Code Online (Sandbox Code Playgroud)