473,395 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How do you build a singleton class in PHP? Can you?

Consider this:

[PHP]
class ActionHandler {

/*-------------------------------------------------------------------------------------------------------------------------------------------------------------------
This class will be a singleton class structure by calling its
constructor by reference only (prefixed by '&'). Is primarly used to
reference its errorArray Array property as a single reference to
allow for static usage
--------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

var $isSuccessful = true; // BOOLEAN PROPERTY DETERMINING IF
ACTION WAS SUCCESSFUL
var $tableName; // DB TABLE NAME PROPERTY
var $fileName; // FILE NAME PROPERTY
var $dbConn; // DB CONNECTION OBJECT
var $dbConnObj; // DB RESOURCE LINK OBJECT
/*---------------------------------------------------------------------------------------------------------------------------------------------------------
Remember that you since this class will be extended by other classes
especially in action.inc.php, for properties to
have value into the class this extends into, you will have to not
"construct" them here since this constructor will not
be called directly by the extended class.
------------------------------------------------------------------------------------------------------------------------------------------------------------*/
function &ActionHandler() { // SINGLETON CONSTRUCTOR
static $errorArray = array(); // ASSOCIATIVE ARRAY PROPERTY
FIELD => ERROR MSG
}

//----------------------------------------------------* GETTER/SETTER
METHODS *--------------------------------------------------------------

function &getErrorArray() { // STATIC ARRAY METHOD
return $this->errorArray;
}
function &getHTMLRedirect($myImmedAction, $additionalQS = '') { //
STATIC HTML/JAVASCRIPT STRING METHOD
global $section, $clientFolderName, $projectFolderName,
$redirectArray;
if ($redirectArray[$section][$myImmedAction] && $myImmedAction) {
$html = "\n<script>\n <!--\n location.href =
'/$clientFolderName/$projectFolderName/index.php?section=$section&action="
..
$redirectArray[$section][$myImmedAction] .
'&success=' . urlencode($this->getSuccessMsg());
$html .= ($additionalQS) ? '&amp;' . urlencode($additionalQS) : '';
$html .= "';\n //-->\n</script>\n<noscript>\n<meta
http-equiv=\"Refresh\"
content=\"1;URL=/$clientFolderName/$projectFolderNameindex.php?" .
"section=$section&action=" .
$redirectArray[$section][$myImmedAction] . '&success=' .
urlencode($this->getSuccessMsg());
$html .= ($additionalQS) ? '&amp;' . urlencode($additionalQS) : '';
$html .= "\">\n</noscript>\n\n";
}
return $html;
}

function &getSuccessMsg() { // STATIC STRING METHOD
global $action, $choice, $db;
return 'Successful ' . strtoupper($action) . ' ' .
strtoupper($choice) . " to database $db - <a
href=index.php?willViewLog=1>View Log</a><p>";
}

function setErrorArray($additionalErrorArray) { // VOID METHOD
if (is_array($this->errorArray) && @sizeof($this->errorArray) > 0 &&
is_array($additionalErrorArray) && @sizeof($additionalErrorArray) > 0)
{
$this->errorArray =& $this->errorArray + $additionalErrorArray;
} elseif (is_array($additionalErrorArray) &&
@sizeof($additionalErrorArray) > 0) {
$this->errorArray =& $additionalErrorArray;
}
}

//--------------------------------------------------* END OF
GETTER/SETTER METHODS
*-------------------------------------------------------------------------

function &convert_to_HTML($content) { // STATIC HTML STRING
METHOD
$content = preg_replace('/[\n\r]/i', '<BR>', $content);
$content = preg_replace('/[\s]/i', '&nbsp;', $content);
return $content;
}

function &convert_to_text($content) { // STATIC TEXT STRING
METHOD
$content = preg_replace('/<br[^>]*>/i', '\n', $content);
$content = preg_replace('/&nbsp;/i', '\s', $content);
return $content;
}

}
[/PHP]

THAT is my entire supposed Singleton class in its actual entirety. It
is set up that way to call static methods upon a static array. That
way, whenever you have this call in your class:

[PHP]
if (somethingsWrong) ActionHandler::setErrorArray('action' =>
'Something is wrong'));
[/PHP]

However, consider this example: I call an instance of a FileGenerator
class from my ActionPerformer->perform() method. FileGenerator class
object's getBackupFile() method does some code and if it breaks:

[PHP]ActionHandler::setErrorArray('action' => 'Something is
wrong'));[/PHP]

Everything in the FileGenerator class object method works just fine
and were I to do this:

[PHP]print_r(ActionHandler::getErrorArray());[/PHP] I see:

Array (action => Something is wrong)
But the moment I leave the getBackupFile() method from FileGenerator
class object and return to the code in ActionPerformer->perform()
method and were I do this:

[PHP]print_r(ActionHandler::getErrorArray());[/PHP] I see:

Array ()
How then in PHP do you assure that anytime I call
ActionHandler::setErrorArray() that the error array, which is supposed
to be static, remains a single-instance entity with a value available
to ALL classes everywhere? How do you build a singleton class in PHP?

Phil
Jul 17 '05 #1
1 2409
With total disregard for any kind of safety measures
so*****@erols.com (Phil Powell) leapt forth and uttered:
How do you build a singleton class in PHP?


class Singleton {
function &instance() {
static $instance = false;
if(!$instance) {
$instance = new Singleton;
}
return $instance;
}
}

$obj =& Singleton::instance();

--
Phil Roberts | Nobody In Particular | http://www.flatnet.net/
Jul 17 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Tim Clacy | last post by:
Is there such a thing as a Singleton template that actually saves programming effort? Is it possible to actually use a template to make an arbitrary class a singleton without having to: a)...
10
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
3
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic...
5
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++...
5
by: Alfonso Morra | last post by:
Hi, I've written a very simple Simpleton design pattern class template. This was supposed to illustrate a point. Although it compiles without nay errors, I get link errors (unresolved external),...
14
by: Angel Tsankov | last post by:
I need to make verifications in release builds. If a verification fails, an error message should be displayed and the program should be aborted. I need this solution to be portable. Then I thought...
12
by: Preets | last post by:
Can anyone explain to me the exact use of private constructors in c++ ?
2
by: keepyourstupidspam | last post by:
Hi, I have a strange build problem. I am building an exe, this exe links to a number of static libraries maybe 20 in all and all are built from my code. I am using the gmake build system...
3
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.