为什么我的函数不返回字符串?

时间:2014-08-09 15:20:37

标签: php recursion

我有一个功能,首先寻找高级品牌添加到字符串。如果没有足够的高端品牌,它会继续并宣传非高端品牌(最多4个品牌)。

我能够回显函数内部的字符串并显示4个品牌,但我无法返回字符串。那是为什么?

$bnames = addBrandNameToTitle($model);
echo $bnames; // This is empty

function addBrandNameToTitle($model, $brandNames = array(), $ispremium = true){
    if($ispremium):
        foreach ($model->brands as $brand):
            if ($brand->isPremium() && count($brandNames)  < 4):
                array_push($brandNames, $brand->name);
            endif;

            if(count($brandNames)  >= 4){
                return implode(',', $brandNames);
            }
        endforeach;
        // If not enough premium, add non-premium brands
        addBrandNameToTitle($model, $brandNames, false);
    else:
        foreach ($model->brands as $brand):
            if (!$brand->isPremium() && count($brandNames) < 4):
                array_push($brandNames, $brand->name);
            endif;
        endforeach;
        $bnames = implode(',', $brandNames);
        echo $bnames; // <-- This lists 4 brands
        return $bnames; // <-- But this is not returning the string. Why?
    endif;
}

1 个答案:

答案 0 :(得分:3)

在此部分代码中,您忘记返回值

// If not enough premium, add non-premium brands
return addBrandNameToTitle($model, $brandNames, false);  // Add a return