2
class Test {
    public function __construct() {
        self::runTest();
        Test::runTest();
    }

    public static function runTest() {
        echo "Test running";
    }
}

// echoes 2x "Test running"
new Test();

Is there any difference between self::runTest() and Test::runTest()? And if so, which one should I use?

self::runTest() when calling the method within the class and Test::runTest() when outside the class?

1
  • self::runTest() when calling the method within the class and Test::runTest() when outside the class? - yes Commented Jan 21, 2013 at 13:40

3 Answers 3

5

you should call self::runTest() from inside the class methods and Test::runTest() outside of the class methods

4

Here's a bit of example code to show what's happening:

class A {
  function __construct(){
     echo get_class($this),"\n"; 
     echo self::tellclass();
     echo A::tellclass();
  }

  static function tellclass(){
    echo __METHOD__,' ', __CLASS__,"\n";
  }

}

class B extends A {
}

class C extends A{
    function __construct(){
        echo "parent constructor:\n";
        parent::__construct();
        echo "self constructor:\n";
        echo get_class($this),"\n";
        echo self::tellclass();
        echo C::tellclass();
    }

    static function tellclass(){
        echo __METHOD__, ' ', __CLASS__,"\n";
    }
}

$a= new A;
// A
//A::tellclass A
//A::tellclass A

$b= new B;
//B
//A::tellclass A
//A::tellclass A

$c= new C;

//parent constructor:
//C    
//A::tellclass A
//A::tellclass A

//self constructor:
//C
//C::tellclass C
//C::tellclass C

    

The take-away point is that A::tellclass() always calls the tellclass method defined in A. But self::tellclass() allows child classes to use their own version of tellclass() if they have one. As @One Trick Pony notes, you should also check out late static binding: https://www.php.net/manual/en/language.oop5.late-static-bindings.php

4

self::runTest() when calling the method within the class and Test::runTest() when outside the class?

exactly!

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