我能否以某种方式从另一个类方法中获取构造函数参数的值而不直接传递它们?
我尝试使用方法 \ReflectionClass
但只能获取属性名称。如何获取参数名称及其值?
Counts
、types
、values
、names
是事先不知道的。
<?php
class Report extends AbstractReport
{
public function __construct($month, $year)
{
$this->month = $month;
$this->year = $year;
}
}
class Report2 extends AbstractReport
{
public function __construct($day, $month, $year, $type = null)
{
$this->day = $day;
$this->month = $month;
$this->year = $year;
$this->type = $type;
}
}
class AbstractReport
{
/**
* Return contructor parameters array
* @return array
*/
public function getParameters()
{
$ref = new \ReflectionClass($this);
if (! $ref->isInstantiable()) {
return [];
}
else {
$constructor = $ref->getConstructor();
return $constructor->getParameters();
}
}
public function getHash()
{
return md5(serialize($this->getParameters()));
}
}
最后,我需要为所有哈希获取不同的唯一值
$report = new Report(10, 2017);
$hash1 = $report->getHash();
$report = new Report2(18, 10, 2017, 'foo');
$hash2 = $report->getHash();
$report = new Report2(01, 02, 2017, 'bar');
$hash3 = $report->getHash();
即所有选项的哈希值必须不同
return $hash1 != $hash2 && $hash2 != $hash3 && $hash1 != $hash3;
任何想法或帮助,提前谢谢你
最佳答案
解决方案。 我只需要重写方法
/**
* Return constructor parameters as array
*
* @return array
*/
protected function getParameters()
{
$ref = new ReflectionClass($this);
if (! $ref->isInstantiable()) {
return [];
}
$parameters = [];
$constructor = $ref->getConstructor();
$params = $constructor->getParameters();
foreach ($params as $param) {
$name = $param->getName();
$parameters[$name] = (string) $this->{$name};
}
return $parameters;
}
输出这个
array:2 [
"month" => "11"
"year" => "2017"
];
关于php - 从另一个方法获取 php 构造函数参数值和名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47270280/