Александр М
Александр М

Reputation: 141

Get php constructor parameters value and names from another method

Can I somehow get the values of the constructor parameters from another class method without passing them directly?

I tried to use the methods \ReflectionClass but could only get the names of attributes. How can I get parameter names with their values?

Counts, types, values, and names of parameters are not known in advance.

<?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()));
    }
}

In the end, I need to get different unique values for all hashes

$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();

Ie the hash must be different for all options

 return $hash1 != $hash2 && $hash2 != $hash3 && $hash1 != $hash3;

Any ideas or help, thank you in advance

Upvotes: 4

Views: 3177

Answers (1)

Александр М
Александр М

Reputation: 141

Solution. I just had to rewrite the method

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

Output this

array:2 [
   "month" => "11"
   "year" => "2017"
];

Upvotes: 10

Related Questions