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');
?>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With