OOP的逻辑错误

Era*_*ray 2 php oop yii

我正在学习Yii Framework.我第一次使用框架,我需要一些建议.我的Controller上有一个getSocials()函数.

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;
    }
Run Code Online (Sandbox Code Playgroud)

(它是私有的,因为我只是从另一个函数调用它).我会逐行解释,

$socials=Socials::model()->find("socials_user=$id");
Run Code Online (Sandbox Code Playgroud)

通过Socials模型从数据库获取socials_user collumn等于$ id的数据.

foreach ($socials as $social)
Run Code Online (Sandbox Code Playgroud)

$ socials作为数组返回,因为有几行,socials_user collumn等于数据库中的$ id.

$allSocial .= "<li><a href=\"#\" rel=\"nofollow\">$type</a></li>";
Run Code Online (Sandbox Code Playgroud)

在foreach循环中,添加<li>...</li>到字符串的结尾,所以$ allSocial将是<li>...</li><li>...</li>...

BUt我得到Undefined变量:allSocial错误.当我从等号(=)前面删除点时,它正在工作.但这次是在foreach循环中,它总是覆盖,最后$ allSocial只包含last<li>...</li>

有任何逻辑错误吗?

San*_*kum 5

$allSocial没有在任何地方定义,你不能将字符串附加到未定义的变量.试试这样:

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;
}
Run Code Online (Sandbox Code Playgroud)