All function's vars are global
Is it possible to make all function's vars global without typing开发者_JS百科 all of them like global $a, $b, $c...
?
Try creating a Static object within your application and assigning variables to that scope, Like so!
<?php
/*
* Core class thats used to store objects of ease of access within difficult scopes
*/
class Registry
{
/*
* @var array Holds all the main objects in an array a greater scope access
* @access private
*/
private static $objects = array();
/**
* Add's an object into the the global
* @param string $name
* @param string $object
* @return bool
*/
public static function add($name,$object)
{
self::$objects[$name] = $object;
return true;
}
/*
* Get's an object out of the registry
* @param string $name
* @return object on success, false on failure
*/
public static function get($name)
{ if(isset(self::$objects[$name]))
{
return self::$objects[$name];
}
return false;
}
/**
* Removes an object out of Registry (Hardly used)
* @param string $name
* @return bool
*/
static function remove($name)
{
unset(self::$objects[$name]);
return true;
}
/**
* Checks if an object is stored within the registry
* @param string $name
* @return bool
*/
static function is_set($name)
{
return isset(self::$objects[$name]);
}
}
?>
Considering this file is one of the first files included you can set any object/array/variable/resource/ etc into this scope.
So lets say you have just made a DB Connection, this is hwo you use it
...
$database = new PDO($dns);
Registry::add('Database',$database);
$DBConfig = Registry::get('Database')->query('SELECT * FROM config_table')->fetchAll(PDO::FETCH_CLASS);
Registry::add('Config',$DBConfig);
No anywhere else within your script you can add or retrieve items.
with Registry::get('ITEM_NEEDED');
This will work in methods functions etc.
Perfect example
function insertItem($keys,$values)
{
Registry::get('Database')->query('INSERT INTO items ('.implode(',',$keys).') VALUES ('.implode(',',$values).')');
}
Hope it helps
No. That'd be an awful thing to do anyways.
You can pass them as arguments and then you won't need the global
keyword:
function(&$a, &$b, &$c)
{
// your code........
}
You can always use $GLOBALS["var"]
instead of $var
. Of course, if you need this, you're most likely doing it wrong.
精彩评论