如何在不使用“使用"的情况下加载类但就像我用过它一样称呼它 [英] How to have class loaded without using "use" but call it as if I used it

查看:22
本文介绍了如何在不使用“使用"的情况下加载类但就像我用过它一样称呼它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了这两个来源,但没有一个对我有用.

I have studied these 2 sources, but none of those works for me.

http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html

Yii2 - 如何自动加载自定义类?

我创建了自定义帮助程序类,我希望将其包含在应用程序的每个模型、控制器和视图中.我使用的是 Yii2 高级应用程序版本 2.0.11,我使用的 IDE 是 PHPStorm

I have created custom helper class which I want to include in every model, controller and view in my application. I am using Yii2 advanced app version 2.0.11, IDE I am using is PHPStorm

问题:

我想要实现的是在每个类开始时不使用 use 关键字,但仍然能够简单地调用 AppHelper::myMethod()在模型、控制器和视图中.这怎么可能?

What I want to achieve is to not use use keyword at the beggining of every class but still be able to simply call AppHelper::myMethod() in models, controllers and views. How is that possible?

我最接近的是使用这个解决方案 https://stackoverflow.com/a/35160997/5395463

Closest I got it working was using this solution https://stackoverflow.com/a/35160997/5395463

所有其他解决方案对我都不起作用.我收到如下错误:

All other solutions did not work for me. I am getting errors like:

PHP Fatal Error – yii\base\ErrorException 
Class 'frontend\controllers\AppHelper' not found

当我不包含 use commons\commands\AppHelper;或者当不使用命名空间时,因为他们建议使用其他设置:

when I simply dont include use commons\commands\AppHelper; or when not using namespace as they suggest there with other settings:

Fatal error: Uncaught exception 'yii\base\UnknownClassException' 
with message 'Unable to find 'common\commands\AppHelper' 
in file: C:\xampp\htdocs\domain.com\web\common/commands/AppHelper.php.
 Namespace missing?' in ...

解决方案:

感谢您的回复,我终于搞定了.https://stackoverflow.com/a/42330631/5395463 解决方案最适合我.因此,我从该类中删除了 namespace,但将其保留在 common\commands 文件夹中,将 require 添加到 frontend/web/index.phpbackend/web/index.php 文件(不确定我是否也应该将它添加到 root 中的 yii 文件中,我没有,到目前为止它仍然运行良好),并进行了更改从 AppHelper::myMethod()\AppHelper::myMethod() 的类调用看起来现在一切正常.

Thanks for your responses, I got it working finaly. https://stackoverflow.com/a/42330631/5395463 solution works best for me. So I removed namespace from that class, but left it in common\commands folder, added require to frontend/web/index.php and backend/web/index.php files (not sure if I should add it to yii file in root too, I didnt, so far it is working good anyways), and changed calls of class from AppHelper::myMethod() to \AppHelper::myMethod() looks like eveything is working now.

推荐答案

不懒惰的程序员的解决方案:

Solution for not lazy coders:

  • 用你的类创建组件,这样你就可以像 \Yii::$app->my_component
  • 一样使用它
  • 即使这太多了,而且您的 IDE 比 Windows 记事本更好,请准备宏为您打印此内容

懒惰程序员的解决方案:

Solution for lazy coders:

  • 将您的类保存在没有命名空间的单个 PHP 文件中.
  • 修改您的入口脚本以包含此类 - 即对于基本项目模板,它是 /web/index.php;添加到那里

require(__DIR__ . '/path/to/MyClass.php');

对于高级项目模板,请正确修改.

For Advanced Project Template modify it properly.

这篇关于如何在不使用“使用"的情况下加载类但就像我用过它一样称呼它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆