你應該包括在每個文件中的類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