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

May 25, 2017 pm 05:41 PM
php

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles