Search This Blog

4/23/2011

SELF

Do you know?

Other day I discovered something basic, but that I did not find at PHP documentation. It is one use of reserved word self.

I used to use self basically to call static methods (inside a class) or to access static attributes (inside a class). I discovered is that it could be used to instantiate an object of the current class (inside a method). Let's see an example of signleton class. Formerly, I used to do like that:

class TestSingleton {
    private static $instance = null;

    /**
     * Private constructor
     */
    private function __construct() {
        // void
    }

    /**
     * Do not allow clones
     */
    public function __clone() {
        throw new Exception('Singleton class');
    }

    /**
     * Returns an instance of current class
     * @return TestSingleton
     */
    public static function getInstance() {
        if (self::$instance === null) {
            $current_class = __CLASS__;
            self::$instance = new $current_class();
        }
        return self::$instance;
    }

    ...
}

Note that I must get the value of __CLASS__ constant and put it on a variable to create an instance dinamicaly (so I could change the class name without affect the rest of the code). However, it is too boring to use a variable only to do that. With the discovered way, I can use the self word as follow:

...

    /**
     * Return an instance of current class
     * @return TestSingleton
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

...

As self is a PHP reserved word, we can not create a class named "self". So, when we call "new self" we are, in fact, creating an object of the current class.

You can also use this word with the operator instanceof to check whether the class of an object is the same of the current class. Formerly:

class Test {

    public function foo($obj) {
        $current_class = __CLASS__;
        if ($obj instanceof $current_class) {
            ...
        }
    }

    ...
}

Now:

class Test {

    public function foo($obj) {
        if ($obj instanceof self) {
            ...
        }
    }

    ...
}

No comments:

Post a Comment