douyu53265 2014-11-11 12:20
浏览 47
已采纳

在try - catch块中使用get_class

Questions

  • Is it possible to instantiate an class with the get_class method in PHP?
  • Is it possible to use get_class into an catch() block to catch an exception from that type of error?

My own try

Whenever using the get_class, it returns the class name as a string. When I tried to instantiate it like this:

$classWhereExceptionObjectIsStored = new classWhereExceptionObjectIsStored();

try {
   //Some code

} catch(get_class($classWhereExceptionObjectIsStored->getExceptionObject $e)) {
   //Do stuff with the exception
}

It didnt work.

The class:

class classWhereExceptionObjectIsStored
{

    public function getExceptionObject($message) {
        return new LogicException($message); //For example
    }
}

Second try

$class = get_class($classWhereExceptionObjectIsStored->getExceptionInstance('hi!'));

try {
   //Some code

} catch($class $e)) {
   //Do stuff with the exception
}
  • 写回答

1条回答 默认 最新

  • dongmu7335 2014-11-11 12:26
    关注

    get_class returns just the name of the class, that's the use of that function. You can instantiate a class dynamically by doing:

    new $class();
    

    Which in your case would probably have to result in something like:

    new get_class($classWhereExceptionObjectIsStored->getExceptionInstance('hi!'));
    

    This doesn't work in a catch block. That's because you don't instantiate anything in a catch block - the only thing you specify there is the exception class you're expecting to get.

    An alternative would be to catch all exceptions:

    catch(Exception $e){}
    

    And then within that catch use the PHP function is_a to check if the thrown exception is of the type you're expecting, like so:

    if(is_a($e, get_class($classWhereExceptionObjectIsStored->getExceptionInstance('hi!'))){}
    

    However, I truly question your motives. I can't think of any use case where this would add functionality, readability, scalability or usability.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计