PHP call to class constant interpreting its name from the contents of a variable

1

I have this code:

if (!empty($filters['status'])) {
    if ($filters['status'] == 'DRAFT') {
        $query .= " AND r.status = :status";
        $paramValues[':status'] = Report::STATUS_DRAFT;
        $paramTypes[':status'] = \PDO::PARAM_STR;
    } elseif ($filters['status'] == 'READY_FOR_REVIEW') {
        $query .= " AND r.status = :status";
        $paramValues[':status'] = Report::STATUS_READY_FOR_REVIEW;
        $paramTypes[':status'] = \PDO::PARAM_STR;
    } elseif ($filters['status'] == 'REJECTED') {
        $query .= " AND r.status = :status";
        $paramValues[':status'] = Report::STATUS_REJECTED;
        $paramTypes[':status'] = \PDO::PARAM_STR;
    } elseif ($filters['status'] == 'APPROVED') {
        $query .= " AND r.status = :status";
        $paramValues[':status'] = Report::STATUS_APPROVED;
        $paramTypes[':status'] = \PDO::PARAM_STR;
    } elseif ($filters['status'] == 'VALIDATED') {
        $query .= " AND r.status = :status";
        $paramValues[':status'] = Report::STATUS_VALIDATED;
        $paramTypes[':status'] = \PDO::PARAM_STR;
    }
}

I wanted to simplify it. I have taken the assignments of $query and $paramTypes out of the ifs:

if (!empty($filters['status'])) {
    $query .= "AND r.status = :status";
    $paramTypes[':status'] = \PDO::PARAM_STR;

    if ($filters['status'] == 'DRAFT') {
        $paramValues[':status'] = Report::STATUS_DRAFT;
    } elseif ($filters['status'] == 'READY_FOR_REVIEW') {
        $paramValues[':status'] = Report::STATUS_READY_FOR_REVIEW;
    } elseif ($filters['status'] == 'REJECTED') {
        $paramValues[':status'] = Report::STATUS_REJECTED;
    } elseif ($filters['status'] == 'APPROVED') {
        $paramValues[':status'] = Report::STATUS_APPROVED;
    } elseif ($filters['status'] == 'VALIDATED') {
        $paramValues[':status'] = Report::STATUS_VALIDATED;
    }
}

Since in all cases, in $filters['status'] always arrives a text in capital letters, which coincides with the last part of the constants that I have defined in the Report class, I thought about composing the name of the constant as a result of the value of $filters . To do this, I do the following:

$state = "STATUS_" . $filters['status'];
$paramValues[':status'] = Report::$state;

However, this gives an error:

  

Access to undeclared static property: Report :: $ state

That is, I'm trying to access the property $state instead of interpreting the text I have in the variable.

Is it possible to compose the name of a constant in some way?

    
asked by Jakala 03.04.2017 в 13:53
source

1 answer

1

You could use the constant function in the following way:

$state = "STATUS_" . $filters['status'];
$paramValues[':status'] = constant('Report::'.$state);

Demo

    
answered by 03.04.2017 / 14:14
source