title: Undefined variable in a method of a class - PHP
body: <p>I would like to know why my following code doesn't work. It is giving me this error: </p>
  
  <blockquote>
    <p>( ! ) Notice: Undefined variable: uname in C:\wamp\www\oops\visibility-levels\public.php on line 8</p>
  </blockquote>
  
  <pre><code>&lt;?php
  class User
  {
      public $uname = "admin";
  
      public function setUsername()
      {
          $this-&gt;uname = $uname;
      }
  
      public function getUsername()
      {
          return $this-&gt;uname;
      }
  }
  
  $user = new User();
  $user-&gt;setUsername();
  echo $user-&gt;getUsername();
  ?&gt;
  </code></pre>
  
  <p>But when I modify my above code to -</p>
  
  <pre><code>&lt;?php
  class User
  {
      public $uname;
  
      public function setUsername($uname)
      {
          $this-&gt;uname = $uname;
      }
  
      public function getUsername()
      {
          return $this-&gt;uname;
      }
  }
  
  $user = new User();
  $user-&gt;setUsername("admin");
  echo $user-&gt;getUsername();
  ?&gt;
  </code></pre>
  
  <p>Then it works fine and gives me following output -</p>
  
  <blockquote>
    <p>admin</p>
  </blockquote>
  
  <p>But I dont understand why I got undefined variable uname in my first segment of code. Any idea?</p>