Safe Extraction Operator in OOP in PHP
The safe extraction operator ?->
allows
safely accessing methods and properties of objects
that can be null
.
Let's look at an example. Suppose we have the following class:
<?php
class User
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
?>
Let's create an object of this class:
<?php
$user = new User('john');
?>
Let's output the value of its property:
<?php
$user = new User('john');
echo $user->name;
?>
Suppose now it happened that instead of
an object we have null
. In this case,
an attempt to access the user's name
will lead to an error:
<?php
$user = null;
echo $user->name; // error
?>
To suppress the error, we can use the safe extraction operator:
<?php
$user = null;
echo $user?->name;
?>
Improve the following code using the safe extraction operator:
<?php
class Employee {
public $name;
public $salary;
public function __construct($name, $salary)
{
$this->name = $name;
$this->salary = $salary;
}
}
$employee = new Employee('john', 1000);
echo $employee->name;
echo $employee->salary;
?>