【问题标题】:Where to include PHP exception in the class?在类中的何处包含 PHP 异常?
【发布时间】:2017-01-22 19:35:40
【问题描述】:

我是 OO PHP 新手...我正在尝试创建一个名为 MyClass 的 PHP 类以及一些应该:

  1. 验证参数是否为数字
  2. 验证参数是否已定义
  3. 如果上述任何一项失败,我需要发送异常并附上解释

我已经完成了 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, protected or publicfunction MyFunction(...) 类似。如果没有可见性说明符,它默认为public,但建议指定方法可见性而不是依赖默认值。

标签: php class exception methods


【解决方案1】:

我会建议这样的事情:

function MyFunction($to, $from, $weight, $cube) {
    if(!$this -> isDefined($to, $from, $weight, $cube)){
        throw new \BadMethodCallException('Arguments are missing');
    }
    if(!$this -> isNumeric($weight, $cube)){
        throw new \InvalidArgumentException('Arguments are not numeric');
    }
    //do stuff
}

这就是你如何处理它:

try{
    $MyClassObject->MyFunction($arg1, $arg2, $arg3, $arg4);
}catch(BadMethodCallException $e){
    //handle missing arguments ...
}catch(InvalidArgumentException $e){
    //handle invalid argumets ...
}

所以,这只是基本用法的一个示例。随意调整它。

注意,如果你在函数中缺少非可选参数,PHP 将产生 E_WARNING

【讨论】:

  • 我已将您的代码添加到我的脚本中,但无法在浏览器中加载它(本地主机当前无法处理此请求。)。顺便说一句,这就是我调用我的方法的方式:quote = new Quotations\MyClass(); echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 3).'您将如何在浏览器中显示该错误?
  • 我无法加载脚本的原因是你忘记了;在第二个 if 语句中
  • 我假设你在课外处理异常,对吧?是否可以创建一个异常并在同一个类中处理它?抱歉这些问题,我只是 OO PHP 的新手...
  • 当然,你可以随时捕捉它,甚至在它被扔掉之后。例外是冒泡的。php.net/manual/language.exceptions.php
  • 感谢您的帮助!最后一个问题 - 您如何在浏览器中显示(返回)此异常消息?我知道如何返回数字、字符串等,但不知道如何处理异常?
猜你喜欢
  • 1970-01-01
  • 2015-07-29
  • 2010-12-08
  • 1970-01-01
  • 2010-09-06
  • 2011-02-07
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多