如何检测类是否不存在而不触发错误
我遇到了一个有趣的困境。在 DataMapper 类中,我生成一个类名,用于从数据库返回的行。
问题是,我的所有类都是自动加载的,并且可以来自很多地方(库、应用程序/模型等),我想检查生成的类名是否确实存在。现在,人们会认为:
try
{
$test = new $className();
}
catch(Exception $ex)
{
// Class could not be loaded
}
但是,当然,php 错误(而不是抛出异常)说找不到该类......不是很有帮助。如果没有重写 Zend_Loader 中的自动加载器来搜索所有目录以查看是否可以加载该类,是否有办法完成此操作?
对于任何想知道为什么我需要这样做而不是仅仅让“未找到类”错误显示的人,如果未找到该类,我想在预先确定的位置生成一个类,以使我的生活像这个项目一样轻松一起去。
提前致谢!
艾米
附注如果你们需要更多信息,请告诉我。
I have run into an interesting dilema. In a DataMapper class, I am generating a class name to be used for returned rows from a database.
The thing is, all of my classes are autoloaded, and can come from many places (library, application/models, etc.) and I wanted to check if the class name generated actually exists. Now, one would think that:
try
{
$test = new $className();
}
catch(Exception $ex)
{
// Class could not be loaded
}
But of course, php errors (instead of throwing an exception) saying the class could not be found... Not very helpful. Short of rewriting the autoloader in Zend_Loader to search all directories to see if the class could be loaded, is there anyway to accomplish this?
For anyone wondering why I would need to do this instead of just letting the Class Not Found error show up, if the class isn't found, I want to generate a class in a pre-determined location to make my life easy as this project goes along.
Thanks in advance!
Amy
P.S. Let me know if you guys need any more info.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PHP 的函数
class_exists()
有一个标志,如果尚未加载类,则触发自动加载器:http://www.php.net/class_exists
所以你只需写
PHP's function
class_exists()
has a flag to trigger the autoloader if the class should not be loaded yet:http://www.php.net/class_exists
So you simply write