1

I know that inside a class, $this is used to refer to the current object and self is used to refer to the current class. For example:

class My_Class {

    function start1() {
        $var = self::hello();

        echo $var;
    }

    function start2() {

        $var = $this->hello();

        echo $var;
    }

    function hello() {
        return 'Hello';
    }
}

$obj = new My_Class;
$obj->start1(); // Hello
$obj->start2(); // Hello

In my example, both $this->hello() and self::hello() appear to do the exact same thing. Can anyone give an example of when I should use $this and when I should use self?

henrywright
  • 10,070
  • 23
  • 89
  • 150

1 Answers1

1

$this cannot be used on static functions.

And $this needs an instantiated object.

class example
{
    public static $mystring ;
    public $anotherString;

    //non-static functions (calling static and non-static variables)
    public function regularFunction() { echo $this->anotherString; } 
    public function regularFnUsingStaticVar() { echo self::$mystring ; }

    //static functions (calling static functions and variables)
    public static function anotherStatFn() { self::staticFunction(); }
    public static function staticFunction() { echo self::$mystring ; }
}

// using static vars and functions
example::$mystring = "Hello World!";
example::staticFunction();           /* Hello World! */

// using non-static vars and functions
$obj = new example();
$obj->anotherString = "Hello World!";
$obj->regularFunction();             /* Hello World! */
Carlos M. Meyer
  • 436
  • 3
  • 9