Magic Methods
<?php
/*
================ MAGIC METHODS AND CONSTANTS ================
When we create a new object, and the constructor method requires a parameter, and we run it without passing one, we risk breaking the code.
Assigning default values will solve this problem.
*/
class Car {
private $model ;
// default value if no value is passed when a new object is created
public function __construct ( $model = null ) {
if ( $model ) {
$this->model = $model ;
}
}
public function getCarModel() {
return 'Car model is: ' . $this->model;
}
public function getObjectInfo() {
return 'The Class Name: ' . __CLASS__ . PHP_EOL .
'This line number: ' . __LINE__ . PHP_EOL .
'The file path: ' . __FILE__ . PHP_EOL .
'Method name where it is being called: ' . __METHOD__ ;
}
}
$car = new Car(); // no value was passed, model will print null (empty string)
echo $car->getCarModel() ;
echo PHP_EOL;
echo $car->getObjectInfo() ;
echo PHP_EOL;
class User {
private $firstName;
private $lastName;
public function __construct( $firstName = 'Toto', $lastName = NULL) {
if ( $firstName ) {
$this->firstName = $firstName ;
}
if ( $lastName ) {
$this->lastName = $lastName ;
}
}
public function getFullName() {
return $this->firstName . ' ' . $this->lastName;
}
}
$user1 = new User('John', 'Rambo') ;
$user2 = new User() ;
$user3 = new User('Bananero') ;
echo $user1->getFullName() . PHP_EOL ;
echo $user2->getFullName() . PHP_EOL ;
echo $user3->getFullName() . PHP_EOL ;