繁体   English   中英

PHP:是否可以在引发异常时调用公共类函数?

[英]PHP: Is it possible to call a public class function inside of an exception throw?

我正在尝试运行此样例演示,但我一直得到一个纯字符串

"getConfiguration:Name (self::getName())is not supported"

(使用self :: getName()时)

或错误消息:

PHP Notice:  Undefined property: Demo::$getName

(使用$ this-> getName()时)

这是我的代码:

    class Demo {
        protected $name = "demo";

        public function __construct() {
          try {
                if(true) {
                    throw new Exception("Name (self::getName())" .
                                        "is not supported");
                }
          } catch(Exception $e){
            echo $e->getMessage(); exit;
          }
        }

       public function getName() {
           return $this->demo;
       }
   }

现在这根本不可能吗,或者我在这里做错了吗?

编辑:

在此之前,我使用$this->name ,但是我宁愿使用一个可能的函数,而不是一个非常糟糕的主意。

您正在静态调用一个不是静态的函数。 引用$ this可能在构造器内部也有问题,特别是如果它失败了。

您还应该更改Exception,使其不包含在字符串中。

throw new Exception("Name (".self::getName().") is not supported");

将您的方法更改为静态访问。 您还必须将变量$ demo设为静态:

   protected static $name;

   public static function getName() {
       return self::$name;
   }

仅仅为了获得回声而抛出异常并没有太大意义。 您应该只是回显您的错误并退出或引发异常:

    public function __construct() {
        throw new Exception("Name (".self::getName().") is not supported");
    }

要么

    public function __construct() {
        echo "Name (".self::getName().") is not supported";
        exit;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM