How to catch PHP "Fatal error: Uncaught TypeError"

Viewed 2332

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');

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

You set the function to accept int therefore you can't assign the string to it, try this code.

remove the int from the function params

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

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