Magic Methods and Constants
Magic methods are methods that start with a double underscore. The __construct() is a magic method. It is used to initialize the properties in a class when we create an object of it.
<?php
class Car {
private $model;
public function __construct($model = NULL)
{
if ($model) {
$this->model = $model;
}
}
public function getCarModel()
{
echo "<p>The car model is " . $this->model . "</p>";
}
}
$car1 = new Car('BMW');
$car1->getCarModel();
Let us create another class and practice what we have learned as below:
<?php
class User {
private $firstName;
private $lastName;
public function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFullName()
{
return $this->firstName . " " . $this->lastName;
}
}
$user1 = new User("John", "Doe");
echo $user1->getFullName();