php - When to use self over $this? -


in php 5, difference between using self , $this?

when each appropriate?

short answer

use $this refer current object. use self refer current class. in other words, use $this->member non-static members, use self::$member static members.

full answer

here example of correct usage of $this , self non-static , 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 example of incorrect usage of $this , self non-static , 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 example of polymorphism $this 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 example of suppressing polymorphic behaviour using self 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 $this->foo() calls foo() member function of whatever >is exact type of current object. if object of type x, >calls x::foo(). if object of type y, calls y::foo(). >self::foo(), x::foo() called.

from http://www.phpbuilder.com/board/showthread.php?t=10354489:

by http://board.phpbuilder.com/member.php?145249-laserlight


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -