【发布时间】:2017-01-22 19:35:40
【问题描述】:
我是 OO PHP 新手...我正在尝试创建一个名为 MyClass 的 PHP 类以及一些应该:
- 验证参数是否为数字
- 验证参数是否已定义
- 如果上述任何一项失败,我需要发送异常并附上解释
我已经完成了 1. 和 2. 但不知道如何处理异常,您需要将它们包含在哪里?内部MyFunction 方法内部isNumeric/isDefined 方法。请您帮忙解决这个问题。
我的脚本:
<?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";
}
}
?>
【问题讨论】:
-
if (!is_numeric($w)) throw new Exception("$w is not numeric"); -
请注意,如果出现异常,如果父/调用者在调用堆栈中的某个位置没有
catch该异常,则异常可以/将一直冒泡到堆栈顶部并以“未处理的异常错误”终止整个脚本。 -
var是 PHP4。使用private,protectedorpublic。function MyFunction(...)类似。如果没有可见性说明符,它默认为public,但建议指定方法可见性而不是依赖默认值。
标签: php class exception methods