Short Answer
Use$thisto refer to the current object. Useselfto refer to the current class. In other words, use$this->memberfor non-static members, useself::$memberfor static members.
Full Answer
Here is an example of correct usage of 
$this and self for non-static and static member variables:<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;
    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}
new X();
?>
Here is an example of incorrect usage of 
$this and self for non-static and static member variables:<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;
    function __construct() {
        echo self::$non_static_member . ' '
           . $this->static_member;
    }
}
new X();
?>
Here is an example of polymorphism with 
$this for member functions:<?php
class X {
    function foo() {
        echo 'X::foo()';
    }
    function bar() {
        $this->foo();
    }
}
class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}
$x = new Y();
$x->bar();
?>
Here is an example of suppressing polymorphic behaviour by using 
self for member functions:<?php
class X {
    function foo() {
        echo 'X::foo()';
    }
    function bar() {
        self::foo();
    }
}
class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}
$x = new Y();
$x->bar();
?>The idea is that$this->foo()calls thefoo()member function of whatever is the exact type of the current object. If the object is oftype X, it thus callsX::foo(). If the object is oftype Y, it callsY::foo(). But with self::foo(),X::foo()is always called.
https://stackoverflow.com/questions/151969/when-to-use-self-over-this
No comments:
Post a Comment