从另一个方法获取php构造函数参数值和名称

时间:2017-11-13 17:37:04

标签: php parameters constructor abstract-class

我可以以某种方式从另一个类方法获取构造函数参数的值而不直接传递它们吗?

我尝试使用方法\ReflectionClass,但只能获取属性的名称。如何获取带有值的参数名称?

Countstypesvaluesnames参数未提前知道。

<?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;

任何想法或帮助,提前谢谢

1 个答案:

答案 0 :(得分:5)

解。 我只需重写方法

/**
 * 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"
];