2

I was looking for info about singleton pattern, I found: http://www.php.net/manual/en/language.oop5.patterns.php#95196

I don't understand:

final static public function getInstance()
{
    static $instance = null;

    return $instance ?: $instance = new static;
}

If it set $instance to null, why this kind of return? Why do not create $instance in the global "space" of the class without set it to null in getInstance?

3 Answers 3

6

You cannot initiate class variables with non-static values, so

class X {
    $instance = new SomeObj();
}

is not permitted.

The code you've posted is one way of going about making sure that only ONE instance of that class is defined.

static $instance = null;

will create the variable and set it to null the first time that method is called. After that, sicne it's been declared static, PHP will ignore that line.

Then the other code can be seen as the following:

if (isnull($instance)) {
    ... first time through this method, so instantiate the object
    $instance = new someobj;
}
return $instance;
Sign up to request clarification or add additional context in comments.

Comments

0

Find following links useful for understanding singleton patterns.

Wikipedia

PHP Patterns

1 Comment

This does not address the OP's question about this specific implementation.
0

In this specific example, the $instance is preceded with the static keyword, inside a function call. This means the variable retain it's state (value) between calls to the function. The nullifing will only happen once, in the initial call to the function.
b.t.w. this is C way of doing singletons...

2 Comments

Why this is the C way? what is PHP way?
Well, PHP is both procedural and OO. The above is the procedural way, and very similar in syntax to how you would do it in C. Take a look in the links you got above, it shows all the modern ways to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.