簡體   English   中英

為什么我的函數不返回字符串?

[英]Why isn't my function returning the string?

我有一個函數,該函數首先尋找要添加到字符串中的高級品牌。 如果沒有足夠的高級品牌,則會繼續投放,並投放非高級品牌(最多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;
}

在這段代碼中,您忘記了返回值

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM