magic-s
magic-s

Reputation: 242

Error handling in PHP class

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.

Upvotes: 0

Views: 127

Answers (2)

Weltschmerz
Weltschmerz

Reputation: 2186

I suggest handling errors in the constructor and throwing exception.

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;
    }

}

client:

include 'class.php';

try {
    $test = new magic('', '', '33');
    $test->printFullname();
} catch (Exception $exc) {
    echo $exc->getMessage(); //error messages
}

Upvotes: 2

Vrac
Vrac

Reputation: 1084

There's no reason you can't use exceptions in this scenario, it's what they are designed for, much more elegant than this kind of $this->geterrors(); stuff.

http://php.net/manual/en/language.exceptions.php

Upvotes: -1

Related Questions