Objects Inside Classes in OOP in PHP
Classes can use objects of other classes. Let's look at an example. Suppose we want to create a user with a first name and last name, and also a city where they live. Suppose we have the following class for a city:
<?php
class City {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
?>
We will pass the first name, last name, and city as parameters to the constructor:
<?php
class User {
public $name;
public $surn;
public $city;
public function __construct($name, $surn, $city) {
$this->name = $name;
$this->surn = $surn;
$this->city = $city;
}
}
?>
In this case, the first and last name will be strings, but the city will be an object of its own separate class:
<?php
$city = new City('luis');
$user = new User('john', 'smit', $city);
?>
Let's output our user's first name:
<?php
echo $user->name;
?>
And now let's output the city name for our user:
<?php
echo $user->city->name;
?>
Given the following class:
<?php
class Employee {
public $name;
public $position;
public $department;
public function __construct($name, $position, $department) {
$this->name = $name;
$this->position = $position;
$this->department = $department;
}
}
?>
Make it so that objects of separate classes are passed to the second and third parameters.
Create an employee object using the class from the previous task.
Output the name, position, and department of the created employee to the console.