开发者

A Logical Mistake on OOP

I'm learning Yii Framework .开发者_运维知识库 I'm working with a framework first time, i need some advices. I have a getSocials() function on my Controller .

private function getSocials($id)
    {
        $socials=Socials::model()->find("socials_user=$id");
        foreach ($socials as $social)
        {
            $type = $social["socials_type"];
            $allSocial .= "<li><a href=\"#\" rel=\"nofollow\">$type</a></li>";
        }
        return $allSocial;
    }

(it's private because i'm calling it from another function only). I'll explain it line by line,

$socials=Socials::model()->find("socials_user=$id");

Getting datas from database which socials_user collumn equals to $id, via Socials model.

foreach ($socials as $social)

$socials returning as an array because there are a few lines which socials_user collumn equals to $id on database .

$allSocial .= "<li><a href=\"#\" rel=\"nofollow\">$type</a></li>";

On foreach loop, adding <li>...</li> to end of string, so $allSocial will be <li>...</li><li>...</li>...

BUt i'm getting Undefined variable: allSocial error . When i remove dot from front of equal symbol (=), it's working. But this time on foreach loop, it's overwriting always and finally $allSocial containing only last <li>...</li>

Are there any logical mistake ?


$allSocial is not defined anywhere, you cant attach a string to an undefined variable. Try it like this:

private function getSocials($id)
{
    $socials=Socials::model()->find("socials_user=$id");
    $allSocial = '';
    foreach ($socials as $social)
    {
        $type = $social["socials_type"];
        $allSocial .= "<li><a href=\"#\" rel=\"nofollow\">$type</a></li>";
    }
    return $allSocial;
}


You need to define $allSocial before you try to concatenate anything to it. You may also want to consider returning an array instead so you can easily access the different strings.

private function getSocials($id) {
    $socials=Socials::model()->find("socials_user=$id");
    $allSocial = array();
    foreach ($socials as $social)
    {
        $type = $social["socials_type"];
        $str = "<li><a href=\"#\" rel=\"nofollow\">$type</a></li>";
        array_push($allSocial, $str);
    }
    return $allSocial; 
}


find function will return only one record which is not an array so foreach will never execute replace the code with following to get it working right :

private function getSocials($id)
{
    $socials=Socials::model()->findAll('socials_user=:socials_user', 
                    array(':socials_user'=>1));
    $allSocial = '';
    foreach ($socials as $social)
    {
        $type = $social["socials_type"];
        $allSocial .= "<li><a href=\"#\" rel=\"nofollow\">$type</a></li>";
    }
    return $allSocial;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜