Skip to content

Instantly share code, notes, and snippets.

@ryanve
Created May 24, 2013 19:29
Show Gist options
  • Save ryanve/5645946 to your computer and use it in GitHub Desktop.
Save ryanve/5645946 to your computer and use it in GitHub Desktop.
PHP data function to get/set data stored in private static hash.
<?php
namespace demo;
/**
* Get or set data.
* @param mixed $key
* @param mixed $val
* @return mixed
*/
function data($key = null, $val = null) {
static $hash;
$hash or $hash = array();
$key instanceof \Closure and $key = $key($hash); # "func arg"
$has = 1 < \func_num_args();
if (null === $key)
return $has ? $val : $hash; # "invalid key" or "get all"
if (true === $key)
return $hash = \is_array($val) ? $val : null; # reset
if (\is_scalar($key))
return $has ? $hash[$key] = $val : (isset($hash[$key]) ? $hash[$key] : null); # set or get
$pre = \is_string($val) ? $val : ''; # optional prefix
foreach ($key as $k => $v)
$hash[$pre . $k] = $v; # set multi
return $hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment