Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing "this" and "self" in PHP
    primarykey
    data
    text
    <blockquote> <p>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.</p> </blockquote> <p><a href="http://board.phpbuilder.com/showthread.php?10354489-RESOLVED-php-class-quot-this-quot-or-quot-self-quot-keyword" rel="nofollow">http://board.phpbuilder.com/showthread.php?10354489-RESOLVED-php-class-quot-this-quot-or-quot-self-quot-keyword</a></p> <pre><code>class Demo { private static $name; private $age; public function __construct($name, $age) { self::$name = $name; $this-&gt;age=$age; } public function show() { echo "Name : ", self::$name, "&lt;br/&gt;"; //Accessing by self echo "Name : ", Demo::$name, "&lt;br/&gt;"; //Accessing by class name echo "Age : ", $this-&gt;age, "&lt;br/&gt;"; } } $demo = new Demo("Tiny", 13); $demo-&gt;show(); </code></pre> <p>This produces the following output.</p> <pre><code>Name : Tiny Name : Tiny Age : 13 </code></pre> <p>What is the difference between <code>self::$name</code> and <code>Demo::$name</code> in the preceding snippet?</p> <hr> <pre><code>class Person1 { private $name; private $address; public function __construct($name,$address) { $this-&gt;name = $name; $this-&gt;address = $address; } public function show() { echo "Name : ", $this-&gt;name, "&lt;br/&gt;"; echo "Address : ", $this-&gt;address, "&lt;br/&gt;"; //Accessing by this } } $p1=new Person1("xxx", "yyy"); $p1-&gt;show(); class Person2 { private $name; private $address; public function __construct($name,$address) { self::$name = $name; self::$address = $address; } public function show() { echo "Name : ", self::$name, "&lt;br/&gt;"; echo "Address : ", self::$address, "&lt;br/&gt;"; //Accessing by self } } $p2=new Person1("xxx", "yyy"); $p2-&gt;show(); </code></pre> <p>Preceding two classes <code>Person1</code> and <code>Person2</code> produce the same output as follows.</p> <pre><code>Name : xxx Address : yyy </code></pre> <p>What is the difference between (as in the <code>Preson1</code> class, the <code>show()</code> method)</p> <pre><code>$this-&gt;name; $this-&gt;address; </code></pre> <p>and (as in the <code>Preson2</code> class, the <code>show()</code> method)</p> <pre><code>self::$name; self::$address; </code></pre> <p><strong>in this context</strong>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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