PHP Self vs this?

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


-12 points

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();

?



9 points

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();
?> 

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.