在测试中访问 private static 属性 in static class
Access private static property in static class in test
是否可以在测试用例中访问 $measurements
属性?
class Performance
{
private static $measurements = [];
public static function createMeasurement()
{
// ...
}
}
到目前为止,我尝试过这样的事情:
$reflection = new \ReflectionClass(get_class(Performance));
$property = $reflection->getProperty('measurements');
$property->setAccessible(true);
但这行不通,因为Use of undefined constant Performance - assumed 'Performance'
。我如何告诉 php 从静态 class 中获取对象?
get_class
接受一个对象作为参数,所以制作一个并传递它
$p = new Performance;
$reflection = new \ReflectionClass(get_class($p)); // or
// $reflection = new \ReflectionClass('Performance'); // without get_class
$property = $reflection->getProperty('measurements');
$property->setAccessible(true);
var_dump($property);
var_dump($property->getValue($p));
会输出
object(ReflectionProperty)#3 (2) {
["name"]=>
string(12) "measurements"
["class"]=>
string(11) "Performance"
}
// my property is an array [1,2,3]
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
同样在您的 class 中,您需要正确定义 createMeasurement
函数
private static function createMeasurement(){
^^
试试这个:
$reflectionProperty = new ReflectionProperty('Performance', 'measurements');
$reflectionProperty->setAccessible(true);
echo $reflectionProperty->getValue();
您还可以在 class 范围内使用 closures. You just need to bind 访问私有属性。
$getMeasurements = function() { return static::$measurements; };
$getPerformanceMeasurements = $getMeasurements->bindTo(null, Performance::class);
$measurements = $getPerformanceMeasurements();
是否可以在测试用例中访问 $measurements
属性?
class Performance
{
private static $measurements = [];
public static function createMeasurement()
{
// ...
}
}
到目前为止,我尝试过这样的事情:
$reflection = new \ReflectionClass(get_class(Performance));
$property = $reflection->getProperty('measurements');
$property->setAccessible(true);
但这行不通,因为Use of undefined constant Performance - assumed 'Performance'
。我如何告诉 php 从静态 class 中获取对象?
get_class
接受一个对象作为参数,所以制作一个并传递它
$p = new Performance;
$reflection = new \ReflectionClass(get_class($p)); // or
// $reflection = new \ReflectionClass('Performance'); // without get_class
$property = $reflection->getProperty('measurements');
$property->setAccessible(true);
var_dump($property);
var_dump($property->getValue($p));
会输出
object(ReflectionProperty)#3 (2) {
["name"]=>
string(12) "measurements"
["class"]=>
string(11) "Performance"
}
// my property is an array [1,2,3]
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
同样在您的 class 中,您需要正确定义 createMeasurement
函数
private static function createMeasurement(){
^^
试试这个:
$reflectionProperty = new ReflectionProperty('Performance', 'measurements');
$reflectionProperty->setAccessible(true);
echo $reflectionProperty->getValue();
您还可以在 class 范围内使用 closures. You just need to bind 访问私有属性。
$getMeasurements = function() { return static::$measurements; };
$getPerformanceMeasurements = $getMeasurements->bindTo(null, Performance::class);
$measurements = $getPerformanceMeasurements();