如何在类方法包含的文件中创建一个常规变量? [英] How can I make a regular variable accessible in files included by a class method?

查看:88
本文介绍了如何在类方法包含的文件中创建一个常规变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php网站,其流动如下所示。请注意我遗漏了大部分代码(无论哪个都是省略号)。



index.php

 包含template.php 
...
$ _template =新模板;
$ _template-> load();
...

template.php

  class pal_template {
...
public function load(){
...
include example.php;
...
}

example.php

  ... 
全局$ _template;
$ _tempalate-> foo();
...

现在,这个工作正常。但是,我最终得到了大量通过$ _template-> load()方法显示的文件,并且在这些文件中,我希望能够使用模板类中的其他方法。 p>

我可以在每个文件中调用全局$ _template,然后它可以正常工作,但如果可能的话,我真的很希望$ _template对象可用,而不必记住宣布它是全球性的。



可以这样做吗,做这件事的最好方法是什么?



我的目标是使这些通过模板类加载的文件非常简单易用,因为它们可能需要由基本上对PHP一无所知的人调整,并且在尝试使用之前可能会忘记放置全局$ _template任何$ _template方法。如果$ _template已经在example.php中可用,我的生活将变得更容易。



谢谢!

解决方案

您可以在添加'example.php'之前定义全局变量。

  global $ _template ; 
include'example.php'

或者你可以这样做:

  $ _ template = $ this; 
include'example.php'

或内部example.php:

  $ this-> foo(); 


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!

解决方案

You can define globals before you include 'example.php'.

global $_template;
include 'example.php'

Or you could do this:

$_template = $this;
include 'example.php'

Or inside example.php:

$this->foo();

这篇关于如何在类方法包含的文件中创建一个常规变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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