WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : PHP 4 And the singleton pattern
Categories : PHP, PHP Classes Click here to Update Your Picture
Joseph Crawford
Date : Sep 22nd 2004
Grade : 4 of 5 (graded 2 times)
Viewed : 15098
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Joseph Crawford
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
Like this code?
Show the author your appreciation.
 

Recently i wrote a code example for using the singleton pattern in PHP 5, and have had several people ask if there was a way to do it in PHP 4. After some research i found that there is in fact a way to do this.

In PHP 4 you could not have static class properties however you can have static variables in a function. Here is the function you will need to use for your classes.

<?php

function &singleton($class) {
    static
$instances;

    if (!
is_array($instances)) {
       
$instances = array();
    }

    if (!isset(
$instances[$class])) {
       
$instances[$class] =& new $class;
    }

    return
$instances[$class];
}
?>


Notice that i have used the & (reference operator) in the above code, this is so that we pass by reference rather than letting php make a copy of the object.

Now that you have this function you can place that anywhere in your files before you class is called or included. Next we will create an example class.

<?php

class Example {
     var
$test;

     function
Example($var) {
         
$this->test = $var;
     }

     function
getTest() {
          return
$test;
     }
}

class
Example1 {
     var
$test;

     function
Example1($var) {
         
$this->test = $var;
     }

     function
getTest() {
          return
$this->test;
     }
}
?>


now with this code you can do something like

<?php

$myExample
=& singleton('Example');

$myExample1 =& singleton('Example1');

$myExample->test = 'just a test';

$myExample1->test = 'another test';

echo
'Example $test: '.$myExample->getTest(); echo '<br>'; echo 'Example1 $test: '.$myExample1->getTest();
?>


The above function was sent in by Dan Cech, from the NYPHP Users Group.
The function i had didnt properly deal with more than one class, his does.
He also altered the way it returned the references.

This will return the static instance of the class and will set the values for each class's $test property, then it will echo them to show you that they are different.

Hopefully this has helped a few people and you now understand how to use the singleton pattern in PHP 4.

Please not that a static variable in php 4 is only good on one page load, meaning that if you navigate to another page $instance is no longer set. You will need to add some session handling in here to do this.

I also have another way to do something similar to this without all this singleton stuff that i will touch on.

If you dont want to get too involved in patterns with php 4 (which i dont think you should do anyway) there is a very simple way to achieve the above.

I have this in a file called global.php and i include the global file in all of my files

<?php

include('class/Cart.php');

session_start();

if ((!isset(
$_SESSION['cart'])) || (!is_object($_SESSION['cart']))) {
     
$_SESSION['cart'] = new cart;
} else {
     
$cart = &$_SESSION['cart'];
}

?>


this code will store the object in a session variable and it will only load a new object if the session object is not found.

basically the same results as above for php 4.

Notice i have have my class file included before the session_start(); In order for this to work you MUST have all classes that you will be storing in a session before the session_start().

Joe Crawford
weberdev@codebowl.com



.htpassword manager for apache
Categories : PHP, PHP Classes, Authentication, Apache
Freshmeat.net XML-RPC - This class is meant to query Freshmeat for information about registered projects.
Categories : PHP, PHP Classes, XML, Web Services
A class for sending email; it has support for To:, Cc:, Bcc: and Reply-To: headers. It requires that you have sendmail installed.
Categories : Email, PHP Classes, PHP
Image Cache
Categories : Graphics, PHP Classes, PHP
Power Form Validation
Categories : PHP, PHP Classes, Data Validation
ADODB Database Wrapper Abstraction Library for PHP: MySQL, MSSQL, Oracle, Interbase,ODBC, Microsoft Access and FoxPro.
Categories : PHP Classes, Databases, PHP, General SQL, ODBC
This class splits the results of the query into multiple pages like what the search engine does.
Categories : PHP Classes, PHP, MySQL, Databases
A PHP Calendar function with CSS : add a cool calendar to any php page by just adding a calendar class based function.
Categories : PHP, PHP Classes, Calendar, Date Time
Simple Mini Poll class library (SimPoll)
Categories : PHP, PHP Classes, Databases, MySQL, Complete Programs
Automatic generation of HTML code for a table. OO interface. Can define colspan, rowspan, table style, cell style, and data style. Simple, but effective.
Categories : PHP, PHP Classes, HTML, HTML and PHP
Sample usage of IPv6 and IPv4 with PHP
Categories : PHP, PHP Classes, Network
PHP MIME Decoder. This class decodes Mime Encoded email message. Attachments are stored in a director. Works with Multipart/alternative, multipart/mixed etc. see http://p3mail.com for example.
Categories : PHP, PHP Classes, Email
SPL and ITERATOR : examples
Categories : PHP, Object Oriented, PHP Classes, Sessions
Simple class that uses GD to draw pie charts. After the class definition there's some sample code to demonstrate how you use the class.
Categories : Graphics, PHP, PHP Classes, GD image library, Charts and Graphs
XML To Array
Categories : PHP, PHP Classes, XML, Arrays