Manipulating Objects in Classes in OOP in PHP
Class methods can accept objects of other classes as parameters and manipulate these objects. Let's look at an example. Suppose we have the following class:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
?>
Suppose we decided to create a class that will manipulate a set of user objects:
<?php
class UsersCollection {
}
?>
We will store user objects as an array in a private property:
<?php
class UsersCollection {
private $users;
public function __construct() {
$this->users = [];
}
}
?>
Let's create a method for adding a new user to the array:
<?php
class UsersCollection {
private $users;
public function __construct() {
$this->users = [];
}
public function add($user) {
$this->users[] = $user;
}
}
?>
And now let's make a method that will display the names of all users:
<?php
class UsersCollection {
private $users;
public function __construct() {
$this->users = [];
}
public function add($user) {
$this->users[] = $user;
}
public function show() {
foreach ($this->users as $user) {
echo $user->getName() . '<br>';
}
}
}
?>
Let's see how our class works. First, let's create its object:
<?php
$uc = new UsersCollection();
?>
Now let's add several users to our collection:
<?php
$uc->add(new User('john'));
$uc->add(new User('eric'));
$uc->add(new User('kyle'));
?>
And now let's call the method that will display the names of all users:
<?php
$uc->show();
?>
Create a class EmployeesCollection
,
which will contain an array of employees.
Add a method to this class for adding a new employee.
Add a method to this class for displaying all employees.
Add a method to this class for calculating the total salary of all employees.
Add a method to this class for calculating the average salary of all employees.