tags:

views:

88

answers:

3

Is it ok to use a singleton method inside of a __constructor to initiate the class if it wasn't already?

+1  A: 

If you create it in each constructor that uses it, then it isn't a singleton.

If you follow this tutorial then it should help you understand how to use the singleton design pattern in php.

http://www.developertutorials.com/tutorials/php/php-singleton-design-pattern-050729/page1.html

James Black
+1  A: 

You can't use a singleton method inside a constructor, as the object has already been created, and you can't return anything. Your singleton method, on the other hand, needs to either return the current object or create a new one.

You can use a single method to do that, however, such as the following:

<?php
class X {
    // ...
    function instance() {
        static $instance;
        if(!is_a($instance, 'X')) {
            $instance = new X();
        }
    }
?>
Ryan McCue
+3  A: 

No -- A singleton method is an alternative to using a constructor.

Instead of saying $session = new Session();

you should say

$session = Session::getStaticSession();

Then define Session::getStaticSession() as a function tht returns an internal static var, and calls "new Session()" if the internal static var is null.

Zak
ok thanks I ust of misunderstood it a little bit, I had the basic idea but now I get it fully I think
jasondavis