Satpal Khatana
Satpal Khatana

Reputation: 11

how to use return type a class in php 7

Upvotes: 1

Views: 66

Answers (2)

Coloured Panda
Coloured Panda

Reputation: 3467

You're in for pain if you return empty objects:

  • If you use database's auto increment ids, then it wont exist on this empty model.
  • Any other required fields will not be filled in. (E.g., book with no author and no content?)

Although in some situations empty state objects are okay, if you have to ask then you most likely will handle it incorrectly anyway.

Since you have to check against this empty object anyway, returning null is still an okay solution. If you're on php7.1 then the return type can stay (note the questionmark).

public static function createBook($book_data): ?BookModel
{
    try {
        $book = new BookModel;
        $book->fill($book_data);
        $book->save();

        return $book;
    }
    catch(\Exception $e) {
       log::error($e->getMessage());

       return null;
    }
}

IMO, a better aproach would be to allow the error to propagate up and let you catch it somewhere else. Looks like you're using laravel, so the error will be logged anyway. So, for example, if you're in a database transaction, the transaction can fail safely:

public static function createBook($book_data): BookModel
{
    $book = new BookModel;
    $book->fill($book_data);
    $book->save();

    return $book;
}

Upvotes: 1

user4524061
user4524061

Reputation:

I say it depends on what you want to do if (in this case) the exception is thrown.

  • If you want to let the app know that something went wrong, you should return false. Returning an empty BookModel is basically saying that everything went fine and it's much easier to check if something is false than checking if an attribute of an object is empty.
  • If it doesn't really mind that the book is empty (i.e. your code doesn't assume books are always filled), I think it is okay to return an empty book. However i'd change the code a bit:

    public static function createBook($book_data): BookModel
    {
        $book = new BookModel();
        try {
            $book->fill($book_data);
            $book->save();
        }
        catch(\Exception $e) {
            log::error($e->getMessage());
        }
        return $book;
    }
    

Upvotes: 0

Related Questions