Reading a Non-Existent Property in OOP in PHP
In the example given in the previous lesson, we applied the magic method
__get
to catch access to
private properties. In fact, this method
can also be useful for catching
access to non-existent properties.
Let's look at a practical example. Suppose
we have a class User
with a first name and
last name, which are public
properties:
<?php
class User
{
public $surn;
public $name;
}
?>
Let's make it so that the object of the class
behaves as if it also has a property
full
, outputting the user's first and last name.
Let's use our magic method
__get
for this:
<?php
class User
{
public $surname;
public $name;
public $patronymic;
public function __get($property)
{
if ($property == 'full') {
return $this->surn . ' ' . $this->name;
}
}
}
?>
Let's test:
<?php
$user = new User;
$user->surn = 'john';
$user->name = 'smit';
echo $user->full; // will output 'john smit'
?>
Create a class Date
with public properties
year
, month
and day
.
Using magic, create a property weekDay
,
which will return the day of the week corresponding to
the date.