Constructor Config and array_get

Some of the functions I use daily don’t exist in the PHP core. But the great thing about programming languages is you can create your own functions.

Here is handy function I’ve been using alot of lately.

Originally created by Andrew Shearer

if (!function_exists('array_get')) {
     function array_get($arr, $key, $default = false) {
         if (array_key_exists($key, $arr)) {
             return $arr[$key];
         }
         else {
             return $default;
         }
     }
}

You might use it in a constructors config array.

class Foo {
  public function __construct(array $config = array()) {
      $this->bar = array_get($config, 'foo', 'my default value');
  }

  public function showValue() {
      return $this->bar;
  }
}

$foo = new Foo();
echo $foo->showValue(); // outputs "my default value"

$foo = new Foo(array( 'foo' => 'new value' ));
echo $foo->showValue(); // outputs "new value"

It can greatly simplfy code.

As an alterative you could use an config default merge.

class Foo {
  public function __construct(array $config = array()) {
      $config = $config + array(
          'foo' => 'my default value'
      );
      $this->bar = $options['foo'];
  }

  public function showValue() {
      return $this->bar;
  }
}

$foo = new Foo();
echo $foo->showValue(); // outputs "my default value"

$foo = new Foo(array( 'foo' => 'new value' ));
echo $foo->showValue(); // outputs "new value"