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

Але*_*р М 2 php parameters constructor abstract-class

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

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

Counts,typesvalues,以及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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,我需要为所有哈希值获得不同的唯一值

$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();
Run Code Online (Sandbox Code Playgroud)

即所有选项的哈希值必须不同

 return $hash1 != $hash2 && $hash2 != $hash3 && $hash1 != $hash3;
Run Code Online (Sandbox Code Playgroud)

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

Але*_*р М 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;
}
Run Code Online (Sandbox Code Playgroud)

输出这个

array:2 [
   "month" => "11"
   "year" => "2017"
];
Run Code Online (Sandbox Code Playgroud)

  • 不错的解决方案,感谢您,我实际上学到了一些新东西。 (2认同)