4

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");
    }
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Luis Pavez
  • 53
  • 1
  • 1
  • 6

3 Answers3

5

Create an array and fill it.

$listPerson = [];   
while($row = mysqli_fetch_array($answer)) {
    $listPerson[] = new Person($row);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
4

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.

Thoby
  • 316
  • 1
  • 6
2

List is a 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[] = new objPerson($row);
}
...
Dharman
  • 30,962
  • 25
  • 85
  • 135
Furkan
  • 415
  • 5
  • 17