Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch PHP "Fatal error: Uncaught TypeError"

I am experimenting with PHP7 type hinting. Following code gives 'fatal error'. I tried few methods to no avail. It works Ok when i give int value. But if i give string it crashes. How can i catch type error without crashing my page. The code is:

<?php 

    class Book{
            public $price;
            public function price(int $price){
                if (is_numeric($price)){
                echo 'This is Number ' . $price;
                }else{
                    echo 'Please enter number';
                } 
            }
        }

    $book = new Book();
    $book->price('Hello');

?>
like image 715
Aagii Avatar asked Oct 25 '25 14:10

Aagii


1 Answers

That's how type hinting works. If you tell PHP to expect an int value for a parameter and you pass it a value which is not an integer you will get a TypeError exception. See the manual.

You can implement your code slightly differently with a try/catch block:

try {
    $book->price('Hello');
}
catch (TypeError $e) {
    echo 'Please enter number';
}

In this case you can simplify the price function to:

public function price(int $price){
    echo 'This is Number ' . $price;
}
like image 57
Nick Avatar answered Oct 27 '25 04:10

Nick