首页 > 解决方案 > Recursive PHP Star-Rating function not working

问题描述

I am trying to write a Star-rating function in PHP to return the result (not just echo it).

My newer version is:

function getRating($rating, $ret = '') {
    if ($rating == 0) { return $ret; }
    if ($rating < 1) {
        $ret .= '<span class="fa fa-star-half-empty"></span>';
        $rating-= 0.5;
    } else {
        $ret .= '<span class="fa fa-star"></span>';
        $rating-= 1;
    }
    getRating($rating, $ret);
}
$var = getRating(5.0);

This returns null. The older version just echo it but I want it to hold the rating in a variable:

function getRating($rating,) {
    if ($rating == 0) { return; }
    if ($rating < 1) {
        echo '<span class="fa fa-star-half-empty"></span>';
        $rating-= 0.5;
    } else {
        echo '<span class="fa fa-star"></span>';
        $rating-= 1;
    }
    getRating($rating);
}
getRating(5.0);

This one shows the <span> with the stars. What I am doing wrong in the first function? Thanks in advance.

标签: phpfunctionrecursionfont-awesome

解决方案


You need to have a return value in your function, and you should call it primarily from the outside. Here is a working example: https://3v4l.org/t2G7F

Code:

function getRating($rating, $ret = '') {
    if ($rating == 0) { return $ret; }
    if ($rating < 1) {
        $ret .= '<span class="fa fa-star-half-empty"></span>';
        $rating-= 0.5;
    } else {
        $ret .= '<span class="fa fa-star"></span>';
        $rating-= 1;
    }
    return getRating($rating, $ret);
}

echo getRating(5.0);

推荐阅读