A Path Less Taken

Breaking with convention in a very conventional fashion. Powered by WordPress

"What would you attempt to do if you knew you could not fail?"
Dr. Robert Schuller

Thursday, October 16, 2008

Category: PHP Development Author: JJ 0 Comments

When you instantiate an object in PHP code it is sometimes desirable to allow for variable parameter setting combinations to create the object.  Although this can be done using default parameters passed to the constructor this can become messy when too many variables are available to be set.  A simpler approach is to allow for an associative array to be passed to the constructor as in the example below.

class MyClass {
   protected $_name = 'Bob' ;
   protected $_address = 'Penny Lane' ;
   protected $_phone = '555-555-5555' ;
 
   public function __construct ($config = array ()) {
      if (array_key_exists ('name', $config))
         $this->_name = $config ['name'] ;
      if (array_key_exists ('address', $config))
         $this->_address = $config ['address'] ;
      if (array_key_exists ('phone', $config))
         $this->_phone = $config ['phone'] ;
}

Although this is a trivial example it demonstrates how to leverage an array passed to a constructor class to initialize a PHP variable.  This is a useful technique that can be employed when building re-usable classes to power your applications.

No comments found. Please enter a comment if you have a question or contribution.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">