Home > Backend Development > PHP Tutorial > Detailed explanation of how to use global variables in PHP

Detailed explanation of how to use global variables in PHP

巴扎黑
Release: 2023-03-07 21:48:02
Original
3517 people have browsed it

This article is a detailed analysis and introduction to several methods of using global variables in PHP. Friends who need it can refer to it

Introduction
Even if you develop a new large-scale PHP program, you will inevitably use global data, because some data need to be used in different parts of your code. Some common global data include: program setting classes, database connection classes, user information, etc. There are many ways to make this data global data, the most commonly used of which is to use the "global" keyword declaration, which we will explain in detail later in the article.
The only disadvantage of using the "global" keyword to declare global data is that it is actually a very poor way of programming, and often leads to bigger problems in the program later, because global data puts you in the code The original separate code segments are all linked together. The consequence is that if you change one part of the code, it may cause other parts to go wrong. So if there are many global variables in your code, then your entire program will be difficult to maintain.

This article will show how to prevent this global variable problem through different techniques or design patterns. Of course, first let's see how to use the "global" keyword for global data and how it works.

Use global variables and the "global" keyword
PHP defines some "Superglobals" variables by default. These variables are automatically globalized and can be used anywhere in the program. Called in places, such as $_GET and $_REQUEST, etc. They usually come from data or other external data, and using these variables usually does not cause problems because they are basically not writable.

But you can use your own global variables. Using the keyword "global" you can import global data into the local scope of a function. If you don't understand "variable usage scope", please refer to the relevant instructions in the PHP manual.
Here is a demonstration example using the "global" keyword:

The code is as follows:

<?php
$my_var = &#39;Hello World&#39;;
test_global();
function test_global() {
    // Now in local scope
    // the $my_var variable doesn&#39;t exist
    // Produces error: "Undefined variable: my_var"
    echo $my_var;
    // Now let&#39;s important the variable
    global $my_var;
    // Works:
    echo $my_var;
}
?>
Copy after login

As you can see in the above example Like , the "global" keyword is used to import global variables. It looks like it works well and is simple, so why do we worry about using the "global" keyword to define global data?
Here are three good reasons:

#1. Code reuse is almost impossible.
If a function depends on global variables, it is almost impossible to use this function in different environments. Another problem is that you can't extract this function and use it in other code.

2. Debugging and solving problems is very difficult.
Tracing a global variable is much more difficult than tracking a non-global variable. A global variable may be redefined in some obscure include file, and even if you have a very good program editor (or IDE) to help you, it will take you several hours to discover the problem.

3. It will be very difficult to understand these codes.
It is difficult for you to figure out where a global variable comes from and what it is used for. During the development process, you may know every global variable, but after about a year, you may forget at least some of them. At this time, you will regret that you used so many global variables.
So if we don’t use global variables, what should we use? Let’s look at some solutions below.
Using Function Parameters
One way to stop using global variables is to simply pass the variable as a parameter to the function, as shown below:

Code As follows:

<?php
$var = &#39;Hello World&#39;;
test ($var);
function test($var) {
    echo $var;
}
?>
Copy after login

If you only need to pass a global variable, then this is a very good or even outstanding solution, but what if you want to pass many values?
For example, if we want to use a database class, a program settings class and a user class. In our code, these three classes are used in all components, so they must be passed to every component. If we use the function parameter method, we have to do this:

The code is as follows:

<?php
$db = new DBConnection;
$settings = new Settings_XML;
$user = new User;
test($db, $settings, $user);
function test(&$db, &$settings, &$user) {
    // Do something
}
?>
Copy after login


Obviously, this is not worth it, and Once we have new objects to add, we have to add one more function parameter to each function. So we need to use another way to solve it.

Use SingletonsOne way to solve the problem of function parameters is to use Singletons instead of function parameters. Singletons are a special class of objects that can only be instantiated once and contain a static method that returns the object's interface. The following example demonstrates how to build a simple singleton:

代码如下:

<?php
// Get instance of DBConnection
$db =& DBConnection::getInstance();
// Set user property on object
$db->user = &#39;sa&#39;;
// Set second variable (which points to the same instance)
$second =& DBConnection::getInstance();
// Should print &#39;sa&#39;
echo $second->user;
Class DBConnection {
    var $user;
    function &getInstance() {
        static $me;
        if (is_object($me) == true) {
            return $me;
        }
        $me = new DBConnection;
        return $me;
    }
    function connect() {
        // TODO
    }
    function query() {
        // TODO
    }
}
?>
Copy after login


上面例子中最重要的部分是函数getInstance()。这个函数通过使用一个静态变量$me来返回这个类的实例,从而确保了只有一个DBConnection类的实例。
使用单件的好处就是我们不需要明确的传递一个对象,而是简单的使用getInstance()方法来获取到这个对象,就好像下面这样:

代码如下:

<?php
function test() {
    $db = DBConnection::getInstance();
    // Do something with the object
}
?>
Copy after login


然而使用单件也存在一系列的不足。首先,如果我们如何在一个类需要全局化多个对象呢?因为我们使用单件,所以这个不可能的(正如它的名字是单件一样)。另外一个问题,单件不能使用个体测试来测试的,而且这也是完全不可能的,除非你引入所有的堆栈,而这显然是你不想看到的。这也是为什么单件不是我们理想中的解决方法的主要原因。

注册模式
让一些对象能够被我们代码中所有的组件使用到(译者注:全局化对象或者数据)的最好的方法就是使用一个中央容器对象,用它来包含我们所有的对象。通常这种容器对象被人们称为一个注册器。它非常的灵活而且也非常的简单。一个简单的注册器对象就如下所示:

代码如下:

<?php
Class Registry {
    var $_objects = array();
    function set($name, &$object) {
        $this->_objects[$name] =& $object;
    }
    function &get($name) {
        return $this->_objects[$name];
    }
}
?>
Copy after login

使用注册器对象的第一步就是使用方法set()来注册一个对象:

代码如下:

<?php
$db = new DBConnection;
$settings = new Settings_XML;
$user = new User;
// Register objects
$registry =& new Registry;
$registry->set (&#39;db&#39;, $db);
$registry->set (&#39;settings&#39;, $settings);
$registry->set (&#39;user&#39;, $user);
?>
Copy after login

现在我们的寄存器对象容纳了我们所有的对象,我们指需要把这个注册器对象传递给一个函数(而不是分别传递三个对象)。看下面的例子:

代码如下:

<?php
function test(&$registry) {
    $db =& $registry->get(&#39;db&#39;);
    $settings =& $registry->get(&#39;settings&#39;);
    $user =& $registry->get(&#39;user&#39;);
    // Do something with the objects
}
?>
Copy after login

注册器相比其他的方法来说,它的一个很大的改进就是当我们需要在我们的代码中新增加一个对象的时候,我们不再需要改变所有的东西(译者注:指程序中所有用到全局对象的代码),我们只需要在注册器里面新注册一个对象,然后它(译者注:新注册的对象)就立即可以在所有的组件中调用。

为了更加容易的使用注册器,我们把它的调用改成单件模式(译者注:不使用前面提到的函数传递)。因为在我们的程序中只需要使用一个注册器,所以单件模式使非常适合这种任务的。在注册器类里面增加一个新的方法,如下所示:

代码如下:

<?
function &getInstance() {
    static $me;
    if (is_object($me) == true) {
        return $me;
    }
    $me = new Registry;
    return $me;
}
?>
Copy after login

这样它就可以作为一个单件来使用,比如:

代码如下:

<?php
$db = new DBConnection;
$settings = new Settings_XML;
$user = new User;
// Register objects
$registry =& Registry::getInstance();
$registry->set (&#39;db&#39;, $db);
$registry->set (&#39;settings&#39;, $settings);
$registry->set (&#39;user&#39;, $user);
function test() {
    $registry =& Registry::getInstance();
    $db =& $registry->get(&#39;db&#39;);
    $settings =& $registry->get(&#39;settings&#39;);
    $user =& $registry->get(&#39;user&#39;);
    // Do something with the objects
}
?>
Copy after login

正如你看到的,我们不需要把私有的东西都传递到一个函数,也不需要使用“global”关键字。所以注册器模式是这个问题的理想解决方案,而且它非常的灵活。

请求封装器
虽然我们的注册器已经使“global”关键字完全多余了,在我们的代码中还是存在一种类型的全局变量:超级全局变量,比如变量$_POST,$_GET。虽然这些变量都非常标准,而且在你使用中也不会出什么问题,但是在某些情况下,你可能同样需要使用注册器来封装它们。
一个简单的解决方法就是写一个类来提供获取这些变量的接口。这通常被称为“请求封装器”,下面是一个简单的例子:

代码如下:

<?php
Class Request {
    var $_request = array();
    function Request() {
        // Get request variables
        $this->_request = $_REQUEST;
    }
    function get($name) {
        return $this->_request[$name];
    }
}
?>
Copy after login

上面的例子是一个简单的演示,当然在请求封装器(request wrapper)里面你还可以做很多其他的事情(比如:自动过滤数据,提供默认值等等)。
下面的代码演示了如何调用一个请求封装器:

代码如下:

<?php
$request = new Request;
// Register object
$registry =& Registry::getInstance();
$registry->set (&#39;request&#39;, &$request);
test();
function test() {
    $registry =& Registry::getInstance();
    $request =& $registry->get (&#39;request&#39;);
    // Print the &#39;name&#39; querystring, normally it&#39;d be $_GET[&#39;name&#39;]
    echo htmlentities($request->get(&#39;name&#39;));
}
?>
Copy after login

正如你看到的,现在我们不再依靠任何全局变量了,而且我们完全让这些函数远离了全局变量。
结论
在本文中,我们演示了如何从根本上移除代码中的全局变量,而相应的用合适的函数和变量来替代。注册模式是我最喜欢的设计模式之一,因为它是非常的灵活,而且它能够防止你的代码变得一塌糊涂。
另外,我推荐使用函数参数而不是单件模式来传递注册器对象。虽然使用单件更加轻松,但是它可能会在以后出现一些问题,而且使用函数参数来传递也更加容易被人理解。

The above is the detailed content of Detailed explanation of how to use global variables in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template