【发布时间】:2017-01-22 20:58:37
【问题描述】:
我是 OO PHP 新手...我正在尝试创建一个名为 MyClass 的 PHP 类和一些应该:
- 验证参数是否为数字
- 验证参数是否已定义
- 如果上述任何一项失败,我需要发送异常并附上解释
当我像这样调用MyFunction 方法时:
$quotation = new Quotations\MyClass();
echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 'a');
测试它是否会抛出异常,但由于某种原因页面没有加载说 - “本地主机当前无法处理此请求”。但是当我这样称呼它时:
$quotation = new Quotations\MyClass();
echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 3);
它工作正常(我可以看到空白页)。
为什么它不允许我在浏览器中打印异常?
我的脚本:
<?php
namespace Quotations;
class MyClass {
var $is_number;
var $is_defined;
private $number;
private $defined;
private function isNumeric($w, $c){
if(is_numeric($w) && is_numeric($c)){
$number = true;
}
else{
$number = false;
}
return $number;
}
private function isDefined($t, $f, $w, $c){
if(isset($t, $f, $w, $c)){
$defined = true;
}
else{
$defined = false;
}
return $defined;
}
function MyFunction($to, $from, $weight, $cube) {
try{
if(!$this -> isNumeric($weight, $cube)){
throw new InvalidArgumentException('Arguments are not numeric');
}
if(!$this -> isDefined($to, $from, $weight, $cube)){
throw new BadMethodCallException('Arguments are missing');
}
}catch(InvalidArgumentException $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}catch(BadMethodCallException $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
?>
【问题讨论】:
-
您缺少 MyClass 声明的右大括号,因此它应该始终作为语法错误而失败。启用错误报告以确保您看到 PHP 的错误输出
-
谢谢,我已经添加了大括号,但输出仍然相同!
-
不要将解决方案编辑到问题中。将其发布为答案。这样,人们就可以看到最初的问题是什么,以及它与解决方案有何不同。
-
@Barmar,如果您愿意,可以发布正确答案,我会将其标记为已解决!
标签: php class exception methods