title: PHP - Creating a trait with variables that cannot be accessed by the using class
body: <h2>The Problem</h2>
  
  <p>I have the following PHP code:</p>
  
  <pre><code>trait Trait1 {
      private $secret; // I want this to be only accessible in Trait1 and not in Foo
  
      public function getSecret() {
          return $this-&gt;secret;
      }
  
      public function setSecret($secret) {
          $this-&gt;secret = $secret;
      }
  }
  
  
  class Foo {
      use Trait1;
  
      public function foo() {
          return $this-&gt;secret; // This returns the $secret in Trait1
      }
  
  }
  
  $foo = new Foo();
  $foo-&gt;setSecret("My secret!");
  echo $foo-&gt;foo();
  </code></pre>
  
  <p>The above code outputs <code>"My secret"</code></p>
  
  <h2>What I Wanted?</h2>
  
  <p>I want the function <code>foo()</code> to not be able to run <code>$this-&gt;secret</code> (in other words to return a run time error). However unfortunately, it uses the private variable in <code>Trait1</code>.</p>
  
  <h2>Why is this a problem?</h2>
  
  <p>The reason I don't like this behaviour is that if I accidently have an overlapping private variable that share the same variable name; it can cause problems if you didn't know you overridden a private variable. </p>
  
  <p>For example:</p>
  
  <pre><code>trait Trait1 {
      private $secret;
  
      public function getTraitSecret() {
          return $this-&gt;secret;
      }
  
      public function setTraitSecret($secret) {
          $this-&gt;secret = $secret;
      }
  }
  
  class Foo {
      use Trait1;
      private $secret; // same variable name as in Trait1
  
      public function setFooSecret($secret) {
          $this-&gt;secret = $secret;
      }
  
      public function getFooSecret() {
          return $this-&gt;secret;
      }
  }
  
  $foo = new Foo();
  $foo-&gt;setTraitSecret("Trait secret!");
  echo $foo-&gt;getTraitSecret(); // returns "Trait secret" as expected and wanted
  echo $foo-&gt;getFooSecret(); // unfortunately also returns "Trait secret"
  
  $foo-&gt;setFooSecret("Inner secret!");
  echo $foo-&gt;getTraitSecret(); // unfortunately returns inner secret
  echo $foo-&gt;getFooSecret(); // returns "Inner secret" as expected and wanted
  </code></pre>
  
  <p>The above code outputs similar to:</p>
  
  <pre><code>Trait secret!
  Trait secret!
  Inner secret!
  Inner secret!
  </code></pre>
  
  <h2>A Solution?</h2>
  
  <p>Is there a good solution to this problem?</p>