Similar question has been asked few days ago about error handling. People explained to me how to get errors from class. And i understand it how to create error names and validate in __construct section but still struggling with multiple functions
class magic
{
/**
* @param string $name
* @param string $surname
* @param int $age
* @throws Exception
*/
public function __construct($name, $surname, $age)
{
$errors = [];
if (empty($name)) {
$errors[] = 'Name is required.';
}
if (empty($surname)) {
$errors[] = 'Surname is required.';
}
if (!empty($errors)) {
throw new Exception(implode('<br />', $errors));
}
$this->name = $name;
$this->surname = $surname;
$this->age = $age;
}
public function printFullname()
{
echo $this->name . ' ' . $this->surname;
}
}
another file:
include 'class.php';
try {
$test = new magic('', '', '33');
$test->printFullname();
} catch (Exception $exc) {
echo $exc->getMessage(); //error messages
}
It works but problem with another function in this class:
class magic
{
/**
* @param string $name
* @param string $surname
* @param int $age
* @throws Exception
*/
public function __construct($name, $surname, $age)
{
$errors = [];
if (empty($name)) {
$errors[] = 'Name is required.';
}
if (empty($surname)) {
$errors[] = 'Surname is required.';
}
if (!empty($errors)) {
throw new Exception(implode('<br />', $errors));
}
$this->name = $name;
$this->surname = $surname;
$this->age = $age;
}
public function printFullname()
{
echo $this->name . ' ' . $this->surname;
}
public function auth()
{
//authentication goes here
if...
$errors[] = 'Error1';
else
$errors[] = 'Error2';
etc...
}
}
another file:
include 'class.php';
try {
$test = new magic('', '', '33');
$test->auth();
} catch (Exception $exc) {
echo $exc->getMessage(); //error messages
}
My function auth() working and return errors as if then echo but i would like to do with array.
$test = new magic('', '', '33');the constructor throws an exception and never returns an instantiated object. Therefore$testwill be null and$test->auth();is not executed at all. Exceptions are maybe not the best way to handle user input errors.InvalidArgumentExceptionin the constructor if some required argument is not as expected. But a method likeauth()should return status codes. Storing the error texts in the class itself is not the best idea, since you might want to present some useful error message to the client. If you return error codes you can then display a message in different languages and so on. But the idea to use typed exceptions (see answer of @GiamPy) would also work.