Skip to content

Instantly share code, notes, and snippets.

@EmanueleMinotto
Created July 13, 2013 10:31
Show Gist options
  • Save EmanueleMinotto/5990279 to your computer and use it in GitHub Desktop.
Save EmanueleMinotto/5990279 to your computer and use it in GitHub Desktop.
PHP Double access utility

Double access utility

This is an utility I made to access to common global variables in a mode I prefer: $_GET -> foo against $_GET['foo'].

Where's the utility?

  • you can use this function for other variables too
  • backward compatibility: array access is allowed too, so $_GET['foo'] is accepted
  • integer and float values will be converted from string to their respective values
  • usage on inclusion
  • prevent not defined cells errors

Globals

When you include this script it will automatically conver arrays in $GLOBALS.

If a variable is not defined you don't have to catch errors because undefined cells will return null.

<?php

// URL is http://hostname/path?lorem=ipsum

$function = require_once 'double_access.php';

var_dump(
    $_GET,
    $_GET -> lorem,
    $_GET['lorem'],
    $_GET['undefined']
);

// object(ArrayObject)[3]
//   public 'lorem' => string 'ipsum' (length=5)
// string 'ipsum' (length=5)
// string 'ipsum' (length=5)
// null

?>

Usage on other variables

<?php

$function = require_once 'double_access.php';

$tmp = array(
    'foo' => array(
        0 => 'bar',
        1 => 5,
        'test' => 6.42,
    ),
);

$function($tmp);

var_dump(
    $tmp['foo'],
    $tmp -> foo,
    $tmp['foo'][0],
    $tmp -> foo[0],
    $tmp -> foo -> test
);

// object(ArrayObject)[1]
//   string 'bar' (length=3)
//   int 5
//   public 'test' => float 6.42
// object(ArrayObject)[1]
//   string 'bar' (length=3)
//   int 5
//   public 'test' => float 6.42
// string 'bar' (length=3)
// string 'bar' (length=3)
// float 6.42

?>
<?php
return call_user_func(function ($globals) {
// real function
$fn = function (&$data) use (&$fn) {
// if there's something that isn't an
// array, it'll not be converted
if (!is_array($data)) {
return;
}
foreach ($data as $key => $value) {
// only arrays can be transformed in ArrayObjects
// the 2nd condition is used to prevent recursion
// other cases are for objects obviously of
// another type that will be converted
if (is_array($value) && $value !== $data) {
$fn($data[$key]);
} elseif ($value === (string) intval($value)) {
$data[$key] = intval($value);
} elseif ($value === (string) floatval($value)) {
$data[$key] = floatval($value);
}
}
$data = new ArrayObject($data, 2);
};
// initially all the global data
// will be covnerted
$fn($globals);
// returning the closure useful
// for developers
return $fn;
}, $GLOBALS);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment