Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Short Answer</h1> <blockquote> <p>Use <code>$this</code> to refer to the current object. Use <code>self</code> to refer to the current class. In other words, use <code>$this-&gt;member</code> for non-static members, use <code>self::$member</code> for static members.</p> </blockquote> <h1>Full Answer</h1> <p>Here is an example of <strong>correct</strong> usage of <code>$this</code> and <code>self</code> for non-static and static member variables:</p> <pre><code>&lt;?php class X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo $this-&gt;non_static_member . ' ' . self::$static_member; } } new X(); ?&gt; </code></pre> <p>Here is an example of <strong>incorrect</strong> usage of <code>$this</code> and <code>self</code> for non-static and static member variables:</p> <pre><code>&lt;?php class X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo self::$non_static_member . ' ' . $this-&gt;static_member; } } new X(); ?&gt; </code></pre> <p>Here is an example of <strong>polymorphism</strong> with <code>$this</code> for member functions:</p> <pre><code>&lt;?php class X { function foo() { echo 'X::foo()'; } function bar() { $this-&gt;foo(); } } class Y extends X { function foo() { echo 'Y::foo()'; } } $x = new Y(); $x-&gt;bar(); ?&gt; </code></pre> <p>Here is an example of <strong>suppressing polymorphic behaviour</strong> by using <code>self</code> for member functions:</p> <pre><code>&lt;?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-&gt;bar(); ?&gt; </code></pre> <blockquote> <p>The idea is that <code>$this-&gt;foo()</code> calls the <code>foo()</code> member function of whatever >is the exact type of the current object. If the object is of <code>type X</code>, it thus >calls <code>X::foo()</code>. If the object is of <code>type Y</code>, it calls <code>Y::foo()</code>. But with >self::foo(), <code>X::foo()</code> is always called.</p> </blockquote> <p>From <a href="http://www.phpbuilder.com/board/showthread.php?t=10354489" rel="noreferrer">http://www.phpbuilder.com/board/showthread.php?t=10354489</a>:</p> <p>By <a href="http://board.phpbuilder.com/member.php?145249-laserlight" rel="noreferrer">http://board.phpbuilder.com/member.php?145249-laserlight</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload