PHP Self vs this?



Hi, this sounds very embarrassing but i've been using too much $this->field keyword for so long i can't remember what's the difference between "php $this" and "php self".

does php "self" has any special functionality besides being called differently? surely there must've been some purpose.

example,
instead of $this->GetMyName(), it becomes self::GetMyName();

?



Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members. (Reference: http://www.phpbuilder.com/board/showthread.php?t=10354489)

Examples:

Here is an example of correct usage of $this and self for non-static and static member variables:


<?php
class {
    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 polymorphism with $this for member functions:


<?php
class {
    function 
foo() {
        echo 
'X::foo()';
    }

    function 
bar() {
        
$this->foo();
    }
}

class 
extends {
    function 
foo() {
        echo 
'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>