1

This question could seem dumb but both ($this and self) works to call a static method.

However, what is the correct way?

I personally tend to use "self" because the private static method is like an utility function which doesn't use any object states.

$data = self::calcSoldeNextMonths('sl', $data, $toSub);
$data = $this->calcSoldeNextMonths('sl', $data, $toSub);
gaetanm
  • 1,394
  • 1
  • 13
  • 25

3 Answers3

5

I, personally, would prefer self::, as it instantly tells me that I am dealing with a static method. It certainly wouldn't be much fun to dig around code where I would have to constantly look up the function declarations just to be sure what context this method operates in.

EDIT Please see @Kakawait's link in the first comment: When to use self vs this. Check out the second most upvoted answer for implications using self (namely the scope resolution).

Community
  • 1
  • 1
aefxx
  • 24,835
  • 6
  • 45
  • 55
1

Static methods should only be called with static:: or self::

self:: means the class and this-> means the current object. And by definition static methods are object independent class methods, i prefer to use self::

Basti Funck
  • 1,400
  • 17
  • 31
  • Not quite, there's also the `static::` keyword to consider from PHP version 5.3 and up. – aefxx Sep 20 '13 at 09:23
  • @aefxx `static` is used for late static bindings which can be used to reference the called class in a context of static inheritance please refer o http://php.net/manual/en/language.oop5.late-static-bindings.php‎ – Shushant Sep 20 '13 at 09:27
  • @Shushant The responder edited his answer. He first stated that: *"[...] the only correct way is **self::*"**. Which is not quite true, as I've merely pointed out. – aefxx Sep 20 '13 at 09:33
0

here is simple example that differentiate self and static and simple way to remember different b/w both of them

self returns the base instance of base object (where self is called)

static returns the current instance of object (either object is extended).

class BaseClass {

public function make()
{
    echo __METHOD__, "\n";
}

public function println()
{
    static::make();
}
}

class BaseClass2{

public function make()
{
    echo __METHOD__, "\n";
}

public function println()
{
    self::make();
}
}

class StaticClass extends BaseClass{

public function make()
{
    echo __METHOD__;
}
}

 class selfMain extends BaseClass2{
public function make()
{
    echo __METHOD__;
}
 }
$obj = new StaticClass();
$obj->println();//return the current instance of object

$obj = new selfMain();
$obj->println();//return the best instance of object
Shushant
  • 1,625
  • 1
  • 13
  • 23
  • Thanks for this detailed answer but I know what is the difference between `$this` and `self`. This is not the question. – gaetanm Sep 20 '13 at 10:04