title: Dynamically creating instance variables in PHP classes
body: <p>I'm not sure if this is a trivial questions but in a PHP class:</p>
  
  <p><strong>MyClass:</strong></p>
  
  <pre><code>class MyClass {
     public $var1;
     public $var2;
  
      constructor() { ... }
  
      public method1 () {
  
      // Dynamically create an instance variable
           $this-&gt;var3 = "test"; // Public....?
  
  
      }
  }
  </code></pre>
  
  <p><strong>Main:</strong></p>
  
  <pre><code>$test = new MyClass();
  $test-&gt;method1();
  echo $test-&gt;var3; // Would return "test"
  </code></pre>
  
  <p>Does this work?? How would I get this to work? Ps. I wrote this quickly so please disregard any errors I made with setting up the class or calling methods!</p>
  
  <p><strong>EDIT</strong>
  What about making these instance variables that I create private??</p>
  
  <p><strong>EDIT 2</strong>
  Thanks all for responding - Everyone is right - I should have just tested it out myself, but I had an exam the next morning and had this thought while studying that I wanted to check to see if it worked. People keep suggesting that its bad OOP - maybe but it does allow for some elegant code. Let me explain it a bit and see if you still think so. Here's what I came up with:</p>
  
  <pre><code>//PHP User Model: 
  
  class User {
      constructor() { ... }
  
      public static find($uid) {
           $db-&gt;connect(); // Connect to the database
  
           $sql = "SELECT STATEMENT ...WHERE id=$uid LIMIT 1;";
           $result = $db-&gt;query($sql); // Returns an associative array
  
           $user = new User();
  
           foreach ($result as $key=&gt;$value)
              $user-&gt;$$key = $value; //Creates a public variable of the key and sets it to value
  
           $db-&gt;disconnect();
      }
  }
  
  //PHP Controller:
  
  function findUser($id) {
  
      $User = User::find($id);
  
      echo $User-&gt;name;
      echo $User-&gt;phone;
      //etc...
  
  }
  </code></pre>
  
  <p>I could have just put it in an associative array but I can never correctly name that array something meaningful (ie. $user->data['name'] ... ugly.) Either way you have to know what is in the database so I do not really understand what the argument is that its confusing, especially since you can just var dump objects for debugging.</p>