是否可以在测试用例中访问$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从静态类中获取对象?
答案 0 :(得分:3)
您还可以使用closures访问私有媒体资源。你只需bind他们到班级范围。
$getMeasurements = function() { return static::$measurements; };
$getPerformanceMeasurements = $getMeasurements->bindTo(null, Performance::class);
$measurements = $getPerformanceMeasurements();
答案 1 :(得分:1)
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)
}
同样在课堂上,您需要正确定义createMeasurement
功能
private static function createMeasurement(){
^^
答案 2 :(得分:1)
试试这个:
controller