简体   繁体   English

所有函数的变量都是全局的

[英]All function's vars are global

是否可以使所有函数的var都成为全局变量,而不用像global $a, $b, $c...那样键入所有变量?

Try creating a Static object within your application and assigning variables to that scope, Like so! 尝试在您的应用程序中创建一个Static对象,然后将变量分配给该作用域,就像这样!

<?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'); 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: 您可以将它们作为参数传递,然后就不需要global关键字:

function(&$a, &$b, &$c)
{
 // your code........
}

You can always use $GLOBALS["var"] instead of $var . 您可以始终使用$GLOBALS["var"]代替$var Of course, if you need this, you're most likely doing it wrong. 当然,如果您需要这样做,很可能您做错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM