0

So I've got a class that I'd like to have it just set defaults if they're not passed in. For example, I can pass it an array called $options.

function new_score($options)
{

}

Then I'd like to have a different function that I can set a var to a default if a key with that var's name doesn't exist in the $options array;

The function definition could look like this:

function _set(&$key, $options, $default)
{
}

I know there's array_key_exists(), and I guess I'm sort of looking for a way to access the variables name.

For example:

$apple = 'orange';

How can I get the string 'apple', so I can look for that key? I know I could take the function _set() and have it look for $key, $var, $options, and $default, but I'd rather abstract it further.

0

3 Answers 3

3
function method($options)
{
  //First, set an array of defaults:
  $defaults = array( "something" => "default value",
                     "something_else" => "another default");

  //Second, merge the defaults with the $options received:
  $options = array_merge($defaults, $options);

  //Now you have an array with the received values or defaults if value not received.
  echo($options["something"]);

  //If you wish, you can import variables into local scope with "extract()"
  //but it's better not to do this...
  extract($options);
  echo($something);
}

References:

http://ar.php.net/manual/en/function.array-merge.php

http://ar.php.net/manual/en/function.extract.php

1
  • Remember: Pass $defaults first to array_merge(): $options = array_merge($defaults, $options); Or put it last if using union of arrays: $options = $options + $defaults; Aug 12, 2010 at 0:43
3

there's two ways of doing this:

One at a time with the ternary operator:

$key = isset($array['foo']) ? $array['foo'] : 'default';

Or, as an array as a whole:

$defaults = array('foo' => 'bar', 'other' => 'default value');
$array = $array + $defaults;
1
  • Maybe you could edit the question so that I understand what you're answering to? :p
    – Artefacto
    Aug 11, 2010 at 23:39
1

How about this:

class Configurable
{
 private static $defaults = array (
  'propertyOne'=>'defaultOne',
  'propertyTwo'=>'defaultTwo'
 );

 private $options;

 public function __construct ($options)
 {
  $this->options = array_merge (self::$defaults, $options);
 } 
}

From the documentation for array_merge:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.