php - 如何捕获 php 中不存在的子对象引发的错误?

标签 php plugins error-handling

我正在努力思考如何在 php 中实现一个好的插件系统。我读了很多关于 Hook 系统和实现这些东西的不同方法的文章,但直到现在我还没有找到任何适合我需要的方法或现有系统。

我想要一个对象(让它成为 $plugins),其中所有使用的插件都可以作为子对象($plugin->$blog)。到目前为止,这没有问题。但是我怎么能捕捉到一个不存在的插件呢?

如果在代码中的某个地方我会使用 $plugin->$blog->loadArticle 或类似的东西调用插件 $blog 并且插件系统没有加载插件,则会引发 fatal error 。是否可以在调试类中捕获和处理这些错误?

谢谢你的想法!请原谅我的英语...... ;-)

最佳答案

好吧,您可以使用魔术 __get() 像这样实现您的 Plugin 对象

class Plugins {
   private $plugins = array();

   public function __get($name) {
       if (!isset($this->plugins[$name]) {
          throw new PluginNotInstalledException(); //this can be catched with try / catch
       }
       return $this->plugins[$name];
   }

   ... //methods addPlugin() etc..
}

关于php - 如何捕获 php 中不存在的子对象引发的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16199291/

相关文章:

android - 当前维护的cordova-plugin-crosswalk-webview 有什么替代方案吗?

python - 容器类是处理错误还是只是引发错误?

php - 为什么我的 bootstrap 导航栏在 bootstrap 4 中不显示内联?

PHP curl 错误 60

php - 从 html <form> 下拉列表中添加数字

ruby - 我应该如何从 HALT 不可用的类中返回 Sinatra HTTP 错误?

php mysql+ 注意 : Array to string conversion in C

javascript - 提交按钮在 php 中不起作用

c++ - Jenkins xUnit 插件问题

javascript - 什么是 .apply jQuery 函数?