php - 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);
推荐阅读
- javascript - 我是否需要知道 jquery 才能学习和处理 react js / angular js
- python - 如何在保持分辨率的同时无损地将 2D 浮点 numpy 数组保存到灰度图像中?
- javascript - 深入比较 javascript 对象并保留对象 1 的键和对象 2 的值
- java - 如何从当前登录的用户 Firebase,Android 中检索值
- python - 在 jupyter notebook 中显示多张图片
- r - 使用 gsub 提取部分字符串
- javascript - 有没有办法将自定义工具提示添加到 highcharts 上钻取的第二级列?
- c - 如何使用termios将控制权返回到C中的终端
- jquery - 让本地机器上的 jquery 脚本更改特定网站上的 HTML 客户端
- ios - 如何将 NSMutableDictionary 添加到数组