Search code examples
phpclassstaticthisself

How to use self and this combined in a static class?


I was wondering how to use the self:: and $this combined in a "static" class?

<?php
class Test
{
    static private $inIndex = 0;

    static public function getIndexPlusOne()
    {
        // Can I use $this-> here?
        $this->raiseIndexWithOne();

        return self::inIndex
    }

    private function raiseIndexWithOne()
    {
        // Can I use self:: here?
        self::inIndex++;
    }
}

echo Test::getIndexPlusOne();

?>

I added the questions in the code above as well, but can I use self:: in a non-static method and can I use $this-> in a static method to call a non-static function?

Thanks!


Solution

  • You can use self in a non-static method, but you cannot use $this in a static method.

    self always refers to the class, which is the same when in a class or object context.
    $this requires an instance though.

    The syntax for accessing static properties is self::$inIndex BTW (requires $).