dongquming3255
2017-04-19 13:51 阅读 86
已采纳

PHP中的对象列表

I have a class called Person, with its getters and setters, and I want to know how I can return a List from Data Layer. In C# I use List and I can return the list, but in PHP I don't know how.

function AllPersons()
{
    try 
    {
        $objConn = new Connection();
        $conn = $objConn ->Connect();
        $sql = "SELECT * FROM PERSON";
        $answer= mysqli_query($cn, $sql);
        if(mysqli_num_rows($answer) > 0)
        {
            while($row = mysqli_fetch_array($answer)) 
            {
                /*here i want to do something like in C#
                  List<Person>listPerson;
                  listPerson.add(objPerson);*/
            }
        }
        else
        {
            return null;

        }
    } 
    catch (Exception $e) 
    {
        //FB::log("nada");
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    dongyi2159 dongyi2159 2017-04-19 13:56

    Create an array and fill it.

    listPerson = [];   
    while($row = mysqli_fetch_array($answer)) {
        listPerson[] = new Person($row);
    }
    
    点赞 评论 复制链接分享
  • dongpao1918 dongpao1918 2017-04-19 13:55
    function AllPersons()
    {
        try 
        {
            $objConn = new Connection();
            $conn = $objConn ->Connect();
            $sql = "SELECT * FROM PERSON";
            $answer= mysqli_query($cn, $sql);
            if(mysqli_num_rows($answer) > 0)
            {
                while($row = mysqli_fetch_array($answer)) 
                {
                    print_r($row);
                }
            }
            else
            {
                return null;
    
            }
        } 
        catch (Exception $e) 
        {
            //FB::log("nada");
        }
    }
    
    点赞 评论 复制链接分享
  • dqtu14636 dqtu14636 2017-04-19 13:55

    In PHP arrays replace the use of Lists/Arrays you'd use in .NET. They're really flexible when it comes down to mutations.

    In this case you'd probably approach it like:

    ...
    
    $persons = array();
    while($row = mysqli_fetch_array($answer)) 
    {
        // Using [] appends the content of $row to the $persons array.
        $persons[] = $row;
    }
    
    ...
    

    Read more about the flexibility of PHPs arrays here.

    点赞 评论 复制链接分享
  • dongshan1959 dongshan1959 2017-04-19 13:59

    List is an dimensionless array in C# (Can also be used in dimensional). The arrays in PHP also dimensionless. So you can use arrays.

    ...
    $listPerson = array();
    while($row = mysqli_fetch_array($answer)) 
                {
                   $listPerson[] = objPerson;
                }
    ...
    
    点赞 评论 复制链接分享

相关推荐