Storing Objects in Arrays in OOP in PHP
Suppose we have the following class User:
User.php<?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:
index.php<?php
require_once 'User.php';
?>
Let's create three objects of our class:
index.php<?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:
index.php<?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:
index.php<?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:
index.php<?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:
index.php<?php
foreach ($users as $user) {
echo $user->name . ' ' . $user->age . '<br>';
}
?>
Задание 1
Create a class City with the
following properties: name, population.
Задание 2
Create 5 objects of the City class,
fill them with data, and store them in an array.
Задание 3
Loop through the array of cities you created and display the cities and their population on the screen.