Marius
Marius

Reputation: 43

PHP Functions Classes Methods Confusion

I am working on some legacy code at the moment and stumbled across a weird class/function call that php.net doesn't seem to explain and I've never seen before:

if(security::instance()->check_client()) {

There is a class security, and there are functions named instance and check_client inside that class. But this seems to call two functions in one statement and pass the one to the other, or at least thats what the outcome suggests. Can someone clarify this one for me?

Upvotes: 2

Views: 64

Answers (4)

Alfwed
Alfwed

Reputation: 3282

This is a classical implementation of the singleton pattern

I suppose your class security looks like this :

class security {
    private static $instance = null;

    private function __construct() {}        

    public static function instance() {
        if (null === self::$instance)
            self::$instance = new security();

        return self::$instance;
    }

    public function check_client() { /* do something */ }
}

What it does is that the static method instance returns an instance of the class security; Which mean that security::instance() instanceof security === true

That's why you can chain the call to the check_client() method as in your exemple

security::instance()->check_client()

This is similar to

$secu = security::instance();
$secu->check_client();

Upvotes: 1

hakre
hakre

Reputation: 197767

I can only assume (as I don't know the underlying code), but it might explain it to you.

First of all functions can return objects. You then call an objects function on the returned object:

security::instance()->check_client()

Is the same like:

$securityInstance = security::instance();
$securityInstance->check_client();

Next to that, by the naming of instance I would assume that security::instance() returns the instance of the a security class, probably a singleton implementation or a factory based on the applications configuration.

Upvotes: 0

Peter Porfy
Peter Porfy

Reputation: 9030

security:instance()

is a static call (so probably a static method)

http://php.net/manual/en/language.oop5.static.php

which returns an instance of some class, which has a member method check_client()

so it returns an object, then you can call any public method on that object.

Upvotes: 1

naivists
naivists

Reputation: 33511

The execution goes like this:

  • first, the static method instance() of the security class is executed
  • it returns an instance of the security class (most likely)
  • then, the check_client method is executed on the returned object

So, since security::instance() is an object, you can call a method on it.

Upvotes: 3

Related Questions