gpt4 book ai didi

php - 为什么 getProperty 通过 PHP ReflectionClass 返回 null

转载 作者:可可西里 更新时间:2023-10-31 23:32:09 26 4
gpt4 key购买 nike

我正在创建一个新的 ReflectionClass,然后将 protected 属性 _products 设置为可访问。它总是返回 null 我在这里做错了吗?我在5.4.11

$project  = new ReflectionClass( $instance_of_object );
$property = $project->getProperty( '_products' );
$property->setAccessible( true );
$products = $property->getValue( $project );

我试图确保在我的单元测试中正确设置了一个属性...

最佳答案

我准备了一个简单的工作示例。如果能执行,那一定是你的代码其他地方出错了:

class The_Class {

private $_products;

public function __construct() {
$this->_products = 'foo';
}
}

$instance_of_class = new The_Class();
$reflClass = new ReflectionClass($instance_of_class);
$member = $reflClass->getProperty('_products');
$member->setAccessible(true);
// Here is an error in your code:
// Note that I'm using $instance_of_class, rather then
// $reflClass as argument to getValue()
var_dump($member->getValue($instance_of_class)); // string(3) "foo"

关于php - 为什么 getProperty 通过 PHP ReflectionClass 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203666/

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