Php 如何在类方法包含的文件中访问正则变量?

Php 如何在类方法包含的文件中访问正则变量?,php,methods,include,global-variables,scope,Php,Methods,Include,Global Variables,Scope,我有一个php站点,其流程如下所示。请注意,我省略了大部分代码(只要有省略号) index.php include template.php ... $_template = new template; $_template->load(); ... template.php class pal_template { ... public function load() { ... include example.php; ... } example.php ... glo

我有一个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();
...
现在,这个很好用。然而,我最终拥有了大量通过$\u template->load()方法显示的文件,在这些文件中,我希望能够使用template类中的其他方法

我可以在每个文件中调用全局$\u模板,然后一切正常,但如果可能的话,我真的希望对象$\u模板可用,而不必记住将其声明为全局

这可以做到吗?最好的方法是什么

我的目标是使这些通过template类加载的文件变得非常简单和易于使用,因为那些对PHP基本一无所知的人可能需要对它们进行调整,他们可能会忘记在尝试使用任何$模板方法之前放置全局$模板。如果$u模板已经在example.php中可用,我的生活就会轻松得多


谢谢

您可以在包含'example.php'之前定义全局变量

global $_template;
include 'example.php'
或者你可以这样做:

$_template = $this;
include 'example.php'
或者在example.php中:

$this->foo();

可以在包含“example.php”之前定义全局变量

global $_template;
include 'example.php'
或者你可以这样做:

$_template = $this;
include 'example.php'
或者在example.php中:

$this->foo();

强烈建议不要使用
global

$_template = new template;
$_template->load();
顺便说一下,考虑一下:

->index.php
$_template = new template;
$_template->load();
->template.php

$_template = new template;
$_template->load();
<?php

$this->showMessage(__FILE__);
->example.php

$_template = new template;
$_template->load();
<?php

$this->showMessage(__FILE__);

强烈建议不要使用
global

$_template = new template;
$_template->load();
顺便说一下,考虑一下:

->index.php
$_template = new template;
$_template->load();
->template.php

$_template = new template;
$_template->load();
<?php

$this->showMessage(__FILE__);
->example.php

$_template = new template;
$_template->load();
<?php

$this->showMessage(__FILE__);

我建议你不要像亚尼克告诉你的那样使用“全球”


您可能需要的是。然后,您可以将模板添加到注册表中,并将其分配给每个对象。一般来说,我建议您学习设计模式。你还可以学到更多的东西。

我建议你不要像亚尼克告诉你的那样使用“global”


您可能需要的是。然后,您可以将模板添加到注册表中,并将其分配给每个对象。一般来说,我建议您学习设计模式。还有一些你可以学到的。

像这样的恶作剧是php名声不好的原因。离题:与其写很多include,不如写一个autoloader函数:像这样的恶作剧是php名声不好的原因。离题:与其写很多include,如果你能写一个自动加载器函数,那就更好了:太好了,这就足够了!!太好了,这就够了!!如果我使用注册表模式,我是否可以让其他编辑“example.php”的人可以使用该变量,而不必声明它?是的。此人必须将此变量从注册表中取出,然后使用它。如果此人需要将此变量提供给代码的其他部分,那么他可以将此信息/变量放回注册表。如果我使用注册表模式,是否可以让其他可能正在编辑“example.php”的人无需声明即可使用此变量?是的。此人必须将此变量从注册表中取出,然后使用它。如果此人需要将此变量提供给代码的其他部分,那么他可以将此信息/变量放回注册表。