title: How to dynamically instantiate an object in PHP?
body: <p>Can we dynamically create and initialize an object in PHP?
  This is the normal code:</p>
  
  <pre><code>class MyClass{
      var $var1 = null;
      var $var2 = null;
      .
      .
      public function __construct($args){
          foreach($args as $key =&gt; $value)
              $this-&gt;$key = $value;
      }
  }
  ---------------------
  $args = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_REQUEST;
  $obj = new MyClass($args);
  </code></pre>
  
  <p>The above code works fine. Please note that the names of <strong>REQUEST</strong> parameters are accurately mapped with the members of class <strong>MyClass</strong>.    </p>
  
  <p>But can we do something like this:</p>
  
  <pre><code>$class = "MyClass";
  $obj = new $class;
  </code></pre>
  
  <p>If we can do like this, then can we initialize <strong>$obj</strong> by using <strong>$args</strong>.</p>
  
  <p>According to <a href="https://stackoverflow.com/questions/2201335/dynamically-create-php-object-based-on-string">this post</a>, <strong>$obj = $class</strong> should work. But it does not work for me. I tried <strong>get_class_vars($obj)</strong>. It threw an exception.</p>
  
  <p>Thanks</p>