简体   繁体   中英

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.

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

You can try this by using pass by reference

 function recGerRating(&$rating, &$html=null){
    if($rating == 0 ) return $html;
    if($rating < 1){
      $html .='<span class="fa fa-star-half-empty"></span>';
      $rating-= 0.5;
      return $html;
    }else{
      $html .= '<span class="fa fa-star"></span>';
      $rating-= 1;
      return recGerRating($rating, $html);
    }
  }
 $r = 5;
 echo recGerRating($r);

Live example : https://3v4l.org/k8RXt

You can pass variable by link. Always returning response from function more expensive operation than passing variable by link and change it. This approach uses less memory.

function getRating($rating, &$ret) {
    if ($rating == 0) { return; }
    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(4.5, $var);
echo $var;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM