如何使类方法包含的文件中的常规变量可访问?
我有一个 php 网站,其流程如下所示。请注意,我省略了大部分代码(只要有省略号)。
index.php
include template.php
...
$_template = new template;
$_template->load();
...
template.php
class pal_template {
...
public function load() {
...
include example.php;
...
}
example.php
...
global $_template;
$_tempalate->foo();
...
现在,这工作正常。然而,我最终得到了大量通过 $_template->load() 方法显示的文件,并且在每个文件中我希望能够使用模板类中的其他方法。
我可以在每个文件中调用全局 $_template,然后一切正常,但如果可能的话,我真的希望对象 $_template 可用,而不必记住将其声明为全局。
这可以做到吗?最好的方法是什么?
我的目标是使通过模板类加载的这些文件非常简单且易于使用,因为它们可能需要由基本上对 PHP 一无所知的人进行调整,并且在尝试使用之前可能会忘记放置全局 $_template任何 $_template 方法。如果 $_template 已经在 example.php 中可用,我的生活会容易得多。
谢谢!
I have a php site which flows as shown below. Please note I'm leaving out most of the code (wherever theres an ellipses).
index.php
include template.php
...
$_template = new template;
$_template->load();
...
template.php
class pal_template {
...
public function load() {
...
include example.php;
...
}
example.php
...
global $_template;
$_tempalate->foo();
...
Now, this works fine. However, I end up having a ton of files that are displayed via the $_template->load() method, and within each of these files I'd like to be able to make use of other methods within the template class.
I can call global $_template in every file and then it all works fine, but if possible I'd really like for the object $_template to be available without having to remember to declare it as global.
Can this be done, and what is the best method for doing it?
My goal is to make these files that are loaded through the template class very simple and easy to use, as they may need to be tweaked by folks who basically know nothing about PHP and who would probably forget to put global $_template before trying to use any of the $_template methods. If $_template were already available in example.php my life would be a lot easier.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在包含“example.php”之前定义全局变量。
或者你可以这样做:
或者在 example.php 中:
You can define globals before you include 'example.php'.
Or you could do this:
Or inside example.php:
强烈不建议使用
global
。顺便说一句,考虑一下:
-> index.php
-> 模板.php
-> example.php
将输出类似的内容
The use of
global
is strongly not recommended.By the way, consider this :
-> index.php
-> template.php
-> example.php
Will output something like
我建议您不要使用“全局”,正如雅尼克也告诉您的那样。
您可能需要的是注册表设计模式。然后您可以将模板添加到注册表并将其赋予每个对象。一般来说,我建议您学习设计模式。 这里是您可以学习的更多内容。
I recommend you to not use "global", as Yanick told you as well.
What you probably need is the Registry design pattern. Then you can add the template to the registry and give it to every object. In general I would recommend you to learn about design patterns. Here are some more you could learn.