Storing Objects in Arrays in OOP in PHP
Suppose we have the following class User
:
<?php
class User
{
public $name;
public $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
?>
Let's connect the file with our class to the index.php
file:
<?php
require_once 'User.php';
?>
Let's create three objects of our class:
<?php
$user1 = new User('john', 21);
$user2 = new User('eric', 22);
$user3 = new User('kyle', 23);
?>
Now let's add the objects we created
into the $users
array:
<?php
$user1 = new User('john', 21);
$user2 = new User('eric', 22);
$user3 = new User('kyle', 23);
$users[] = $user1;
$users[] = $user2;
$users[] = $user3;
var_dump($users);
?>
We can shorten our code by getting rid of the variables:
<?php
$users[] = new User('john', 21);
$users[] = new User('eric', 22);
$users[] = new User('kyle', 23);
var_dump($users);
?>
We can shorten the code even more by immediately creating an array of objects:
<?php
$users = [
new User('john', 21),
new User('eric', 22),
new User('kyle', 23)
];
var_dump($users);
?>
Now let's loop through our array of objects and display the object properties on the screen:
<?php
foreach ($users as $user) {
echo $user->name . ' ' . $user->age . '<br>';
}
?>
Create a class City
with the
following properties: name
, population
.
Create 5
objects of the City
class,
fill them with data, and store them in an array.
Loop through the array of cities you created and display the cities and their population on the screen.