JasonDavis
JasonDavis

Reputation: 48983

singleton inside of a construct method in PHP?

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

Upvotes: 0

Views: 339

Answers (3)

Zak
Zak

Reputation: 25237

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.

Upvotes: 3

Ryan McCue
Ryan McCue

Reputation: 1658

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();
        }
    }
?>

Upvotes: 1

James Black
James Black

Reputation: 41838

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

Upvotes: 1

Related Questions