这期内容当中小编将会给大家带来有关PHP中获取对象属性的方法有哪些,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体如下:
class TestClass { private $a; protected $b; public $c; public $d; public static $e; private function funcA() { } protected function funcB() { } public function funcC() { } public function getPropertyMethodOne() { echo "[get_object_vars]", PHP_EOL; $vars = get_object_vars($this); foreach ($vars as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } } public function getPropertyMethodTwo() { echo "[foreach object]", PHP_EOL; foreach ($this as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } } public function getPropertyMethodThree() { echo "[reflection]", PHP_EOL; $class = new ReflectionClass($this); foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { if (!$property->isStatic()) { echo $property->getName(), ' => ', $property->getValue($this), PHP_EOL; } } } }
测试代码一
$obj = new TestClass(); echo "[get_object_vars]", PHP_EOL; $vars = get_object_vars($obj); foreach ($vars as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } echo "[foreach object]", PHP_EOL; foreach ($obj as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } echo "[reflection]", PHP_EOL; $class = new ReflectionClass($obj); foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { if (!$property->isStatic()) { echo $property->getName(), ' => ', $property->getValue($obj), PHP_EOL; } }
输出:
[get_object_vars]
c =>
d =>
[foreach object]
c =>
d =>
[reflection]
c =>
d =>
可见,当着三种方法用在类的外部时,结果是一样的。get_object_vars()
和foreach是获取到的是对象的public non-static属性,而通过反射的话则需要手动筛选出public non-static属性。
测试代码二
$obj = new TestClass(); $obj->getPropertyMethodOne(); $obj->getPropertyMethodTwo(); $obj->getPropertyMethodThree();
输出
[get_object_vars]
a =>
b =>
c =>
d =>
[foreach object]
a =>
b =>
c =>
d =>
[reflection]
c =>
d =>
可见,get_object_vars()
和foreach用在类内部时,private、protected、public的实例属性都能获取到。反射就不用说了,通过手动筛选,各种类型的属性都能获取到。
上述就是小编为大家分享的PHP中获取对象属性的方法有哪些了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。