我有一个遵循单例模式的类的对象。我需要在一个文件中初始化它,然后在其他文件中使用它。我不知道该怎么做,下面是我尝试过的:
//myClass.php
class myClass
{
private static $instance = null;
private function __construct($args)
{
//stuff
}
public function Create($args)
{
self::$instance = new myClass($args);
return self::$instance;
}
public function Get()
{
return self::$instance;
}
}
//index.php
<?php
require_once('myClass.php');
$instance = myClass::Create($args);
?>
<a href="test.php">Test Me!</a>
//test.php
echo(is_null(myClass::Get())); //displays 1所以问题是,在test.php中,myClass::get()总是返回null!
我还尝试将实例存储在$_SESSION中,这给出了相同的结果。你能给我指出正确的方向吗?
发布于 2012-03-27 20:37:02
您应该将带有类定义的file包含在使用它的每个文件中(并且应该在使用它之前将其包含在内)。
<?php // filename: test.php
include_once("myClass.php");
$oClassInstance = myClass::Get();
var_dump($oClassInstance);顺便说一句
您不需要定义这两个方法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();更新
如果你必须将一些参数放入构造函数中,只需使用预定义的参数:
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;
}应答
很抱歉,你不得不滚动几个屏幕才能找到这个=))你不能在你的上下文中使用myClass::Get()的原因是你有两个脚本,这意味着-两个不同的程序。单例应该在单个应用程序(一个脚本)中使用。
因此,在您的情况下,正确的用法是模块系统:- 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你的链接将是:
发布于 2012-03-27 20:32:50
在创建新对象之前,Create()函数需要检查$instance属性是否已经有一个值。例如
public function Create()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}在test.php中,您可以只调用myClass::Create(),而不需要使用Get()函数
https://stackoverflow.com/questions/9709453
复制相似问题