【发布时间】:2009-09-23 01:09:53
【问题描述】:
我现在很困惑。在我关于这个问题的上一篇文章中,答案是使用单例来确保一个对象只启动一次,但我遇到了相反的问题。
如果我有一个名为 index.php 的文件,然后我将这些文件包含在其中,class1.php、class2.php、 class3.php、class4.php。
在index.php我会,
<?PHP
$session = new Session();
require_once '/includes/class1php';
require_once '/includes/class2.php';
require_once '/includes/class3.php';
require_once '/includes/class4.php';
?>
然后在所有 4 个测试文件中,我将尝试从 会话类 访问一个名为 get() 的方法,假设会话类文件已包含在index.php 页面也是如此。
现在如果我尝试使用...
$testvar = $session->get($var1);
在任何测试类文件中我都会收到此错误
Fatal error: Call to a member function get() on a non-object
代码没有错误的唯一方法是如果我使用
$session = new Session();
在每个文件中。
当已经在 index.php 文件中初始化类时,如何修复/避免必须在每个文件中初始化该类?
目标是让我在 index.php 之类的 1 个文件中启动一个类,然后将类文件包含到该页面中,要注意的是大多数类都使用其他类的方法,所以如果我不这样做会很好必须启动每个文件中的每个类
【问题讨论】:
-
在这里也可以使用单例而不是全局。
-
@Frank Farmer 从我的测试中它实际上没有帮助,在我的情况下,类/对象总是在索引文件中启动 1 次,但尝试在另一个类中使用 1 个类,即使它是已经开始了,除非我使用全局,否则存在范围问题,也许我遗漏了一些东西,但我无法获得单身人士来帮助解决该范围问题