1

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!

4 Answers 4

2

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 $).

0

You can't. A static method cannot communicate with methods or properties that require an instance of the class (i.e. non-static properties/methods).

Maybe you're looking for the singleton pattern?

3
  • worth to mention: singleton is treated as anti-pattern nowadays.
    – KingCrunch
    Commented Mar 28, 2012 at 11:20
  • I still doubting about the fact if I should use a singleton pattern or a static class for my database class. Singleton looks better, but you can have only 1. With the fact that in the future I will have to migrate my database I would like to have 2 instances and then a static class would be nicer. Next to that a static class is faster then a singleton pattern, if I see the benchmarks on the great WWW. Commented Mar 28, 2012 at 11:36
  • @pascalvgemert - If you want more than one instance, what are you trying to achieve with static methods and properties? These are "per-class" and not "per-instance".
    – Björn
    Commented Mar 28, 2012 at 11:58
0

You can use self::$inIndex in a non-static method, because you can access static things from non-static methods.

You cannot use $this->inIndex in a static method, because a static method is not bound to an instance of the class - therefore $this is not defined in static methods. You can only access methods and properties from a static method if they are static as well.

0

This would work ( http://codepad.org/99lorvq1 )

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

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

        return self::$inIndex;
    }

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

echo Test::getIndexPlusOne();

you can't use $this inside a static method as there is no instance

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.