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

标签 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;

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

最佳答案

解决方案。 我只需要重写方法

/**
 * 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/

相关文章:

php - 无法在 TinyMce Wordpress 上保持全屏(查看 -> 全屏)

c++ - 为发送到方法的参数分配的大小

php - 我无法在函数中获取配置变量值作为参数

c# - 无参数构造函数

java - if、else if 和 else 语句? java

php - 使用 PHP + GhostScript 裁剪 PDF 奇偶页

php - 如何使用 Laravel 上传视频

php - 使用数据透视模型找不到 Laravel 基表

c - 如何修改已传递给 C 函数的指针?

hibernate - JPA 2.0 : How to avoid full class name in `SELECT NEW full.class.Name` ?