[英]PHP: Is it possible to call a public class function inside of an exception throw?
I am trying to get this litte demo to run, but I keep getting a plain string 我正在尝试运行此样例演示,但我一直得到一个纯字符串
"getConfiguration:Name (self::getName())is not supported"
(when using self::getName()) (使用self :: getName()时)
or an error-messege: 或错误消息:
PHP Notice: Undefined property: Demo::$getName
(when using $this->getName()) (使用$ this-> getName()时)
This is my Code: 这是我的代码:
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;
}
}
Now is this simply not possible or am I doing something wrong here?! 现在这根本不可能吗,或者我在这里做错了吗?
EDIT: 编辑:
Before this I got this working with $this->name
, but I would rather use a function if it is possible and not somehow a very bad idea. 在此之前,我使用
$this->name
,但是我宁愿使用一个可能的函数,而不是一个非常糟糕的主意。
You are calling a function statically that is not static. 您正在静态调用一个不是静态的函数。 Referencing to $this might also be problematic inside a construcotr, especially if it failed.
引用$ this可能在构造器内部也有问题,特别是如果它失败了。
You should also change your Exception to not contain the call inside a string. 您还应该更改Exception,使其不包含在字符串中。
throw new Exception("Name (".self::getName().") is not supported");
Change your method to static access. 将您的方法更改为静态访问。 You will also have to make your variable $demo static:
您还必须将变量$ demo设为静态:
protected static $name;
public static function getName() {
return self::$name;
}
Throwing an exception just to get an echo doesnt make that much sense. 仅仅为了获得回声而抛出异常并没有太大意义。 You should either just echo your error and exit or throw an exception:
您应该只是回显您的错误并退出或引发异常:
public function __construct() {
throw new Exception("Name (".self::getName().") is not supported");
}
OR 要么
public function __construct() {
echo "Name (".self::getName().") is not supported";
exit;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.