是否可以使所有函数的var都成为全局变量,而不用像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
否。无论如何,这将是一件可怕的事情。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.