使用 PHP 重载静态属性
我正在尝试自动化访问我使用的框架(CodeIgniter)中的库的过程,但遇到了一些问题。
Codeigniter 目前加载这样的库:
$this->CI->load->library('name');
$this->CI->name->method();
不用说,这是一大堆代码,可以用更少的资源来实现。
我想像这样访问我的库:
_Lib::name->method();
然后 _Lib 类将负责加载正确的库(或者在本例中将该库的加载定向到加载器类)。
但是,上面的代码会导致错误“意外的 T_OBJECT_OPERATOR”。
我的最终目标是能够与库对话并让它们使用尽可能少的代码按需加载,并且无需初始化全局变量。
有什么想法吗?请记住,它需要看起来尽可能可用且不言自明。
我想避免使用像 _Lib('name')->method() 这样的东西,因为每次都写起来非常乏味。
编辑:
我最终创建了一个默认库,我从中扩展了我的库,默认库具有将其他库(或模型,或帮助程序,或..等)加载到适当的位置的属性。装载机,所以我可以做
$this->lib->name->method();
谢谢大家的回答
I'm trying to automate the process of accessing libraries in the framework I use (CodeIgniter) but am running in to some issues.
Codeigniter currently loads libraries like this:
$this->CI->load->library('name');
$this->CI->name->method();
Needless to say that this is a whole bunch of code for something that could be achieved with far less.
I would like to access my lib like this:
_Lib::name->method();
The _Lib class will then take care of loading the right lib (or directing the loading of that lib to the loader class in this case).
However, above code results in error "unexpected T_OBJECT_OPERATOR".
My end goal is to be able to talk to libraries and have them load on-demand with as little code as possible, and without initializing a global variable.
Any ideas? Keeping in mind that it needs to look as usable and self-explanatory as possible.
I'd like to avoid using something like _Lib('name')->method() as it's quite tedious to write that every time.
Edit:
I ended up creating a default Library which I extend my Libraries from, the default Library has properties which direct the loading of other libraries (or models, or helpers, or .. etc) to the appropreate loader, so I can do
$this->lib->name->method();
Thanks everyone for your answers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按照您编写的方式,_Lib::name 是一个类常量。您的意思是
_Lib::$name->method();
吗?The way you've written it, _Lib::name is a class constant. Did you mean
_Lib::$name->method();
?“意外的
T_OBJECT_OPERATOR
” 错误意味着您对_Lib::name
的调用未返回用于链接方法调用的对象。从技术上讲,_Lib::name
返回_Lib
中类常量name
的值。您正在尝试执行此操作,但常量无法容纳对象,因此没有
->
。您不想将库转换为静态调用,因为任何静态的东西都会耦合到全局范围并且更难测试。只需继续使用 CI 提供的开箱即用的功能即可。
如果您想让一个类来全局管理其他类,请考虑使用 依赖注入 容器,就像Symfony 组件。
The "unexpected
T_OBJECT_OPERATOR
" error means that your call to_Lib::name
did not return an object from which to chain off the method call. Technically,_Lib::name
returns the value of the class constantname
in_Lib
. You are trying to dobut a constant cannot hold an object, so no
->
.You do not want to convert your library to static calls, because anything static couples to the global scope and is much harder to test. Just keep using what CI offers out of the box.
If you want to have one class to globally manage your other classes, consider using a Dependency Injection Container, like the one offered in Symfony Components.