你应该包括在每个文件中的类difinition文件它在哪里使用(并且在使用之前应该包括它)。
<?php // filename: test.php
include_once("myClass.php");
$oClassInstance = myClass::Get();
var_dump($oClassInstance);
BTW
你并不需要定义这两个方法Create
和Get
。您可以创建只有一个方法叫getInstance
:
// only one instance of the class
private static $_oInstance = null;
public static function getInstace()
{
if (!self::$_oInstance)
{
self::$_oInstance = new self();
}
return self::$_oInstance;
}
然后你就可以使用它像:
<?php // filename: index.php
include_once("myClass.php");
// if instance does not exist yet then it will be created and returned
$oClass = myClass::getInstace();
<?php // filename: test.php
include_once("myClass.php");
// the instance already created and stored in myClass::$_oInstance variable
// so it just will be returned
$oClass = myClass::getInstance();
UPD
如果你把一些参数到构造方法仅使用预定义参数:
private function __construct($aArg)
{
// this code will be launched once when instance is created
// in the any other cases you'll return already created object
}
public static function getInstance($aArgs = null)
{
if (!self::$_oInstance)
{
self::$_oInstance = new self($aArgs);
}
return self::$_oInstance;
}
ANSWER
对不起,你必须滚动几屏找到这个=))) 为什么你不能在你环境中使用myClass::Get()
的原因是,你有2个脚本,这意味着 - 两个不同的程序。 应该在单个应用程序中使用单例(一个脚本)。
所以你的情况,正确的使用将是模块系统: - 的index.php - main.php - test.php的
// file: index.php
include_once "myClass.php"
$module = $_GET["module"];
include_once $module ".php";
// file: main.php
$oClass = myClass::Create($someArgs);
var_dump($oClass); // you'll see you class body
// file: test.php
$oClass= myClass::Get();
var_dump($oClass); // you'll see the same class body as above
而且你的链接将是:
- index.php?module = main
- index.php?module = test
忘记单例,你不需要它们在PHP中。你在找什么叫做会话。为什么你的会议不工作我会说这首先需要一些基本的调试。 HTTP:// PHP。net/session – hakre 2012-07-01 10:54:27