我正在尝试使用PHP7类型提示。 以下代码给出“致命错误”。我尝试了几种方法都没有用。 当我给出int值时,它工作正常。但是,如果我给字符串,它会崩溃。如何在不使页面崩溃的情况下捕获类型错误。代码是:
<?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');
?>
答案 0 :(得分:1)
这就是类型提示的工作方式。如果您告诉PHP期望参数使用int
值,并且将非整数值传递给它,则会得到TypeError
异常。参见manual。
您可以使用try / catch块实现代码稍有不同:
try {
$book->price('Hello');
}
catch (TypeError $e) {
echo 'Please enter number';
}
在这种情况下,您可以将price
函数简化为:
public function price(int $price){
echo 'This is Number ' . $price;
}
答案 1 :(得分:0)
您将函数设置为接受int
,因此无法为其分配字符串,
试试这个代码。
从函数参数中删除
int
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');