I still playing with PHP and OOP. But not understand how to pull back errors from the class.
index file
include 'class.php';
$test = new magic('', '', '33');
$test->getfullname();
foreach ($test->get_errors() as $error) {
echo $error . '<br>';
}
class:
class magic
{
private $name;
private $surname;
private $age;
private $errors = array();
function __construct($name, $surname, $age)
{
$this->name = $name;
$this->surname = $surname;
$this->age = $age;
}
public function get_errors()
{
return $this->errors;
}
public function getname()
{
if (!empty($this->name)) {
return true;
} else {
array_push($this->errors, 'Please check name');
return false;
}
}
public function getsurname()
{
if (!empty($this->surname)) {
return true;
} else {
array_push($this->errors, 'Please check surname');
return false;
}
}
public function getfullname()
{
if (($this->getname()) && ($this->getsurname())) {
echo $this->name . ' ' . $this->surname;
}
}
}
My question is why when name or surname is empty then returning please check name or surname but when both are empty then return only first? How to candle these type errors in PHP class and what is best practice to do that? I don't think i can use try/catch exceptions in this scenario.