gpt4 book ai didi

php - 在类中查找属性的范围

转载 作者:可可西里 更新时间:2023-11-01 13:57:49 24 4
gpt4 key购买 nike

class ParentClass
{
public function list()
{
foreach ($this as $property => $value)
{
if (is_public($this->$property))
echo 'public: ';
else if (is_protected($this->$property))
echo 'protected: ';
echo "$property => $value" . PHP_EOL;
}
}
}

class ChildClass extends ParentClass
{
protected $Size = 4;
protected $Type = 4;
public $SubT = 1;
public $UVal = NULL;
}

$CC = new ChildClass;
$CC->list();

最佳答案

使用ReflectionProperty,这是可能的。如果你想让它不那么冗长,你可以创建一个辅助函数:

<?php
function P($obj, $name)
{
return new ReflectionProperty($obj, $name);
}

class Foo
{
public $a;

public function __construct()
{
foreach (array_keys(get_object_vars($this)) as $name)
{
if (P($this, $name)->isPublic())
{
echo "Public\n";
}
}
}
}

new Foo();

?>

关于php - 在类中查找属性的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3847351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com