Reputation: 1247
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!
Upvotes: 1
Views: 199
Reputation: 76880
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
Upvotes: 0
Reputation: 26730
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.
Upvotes: 0
Reputation: 522024
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 $
).
Upvotes: 2
Reputation: 29381
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?
Upvotes: 0