php global variable is invalid

WBOY
Release: 2016-07-29 09:04:11
Original
958 people have browsed it

For PHP beginners, when using the global keyword , you may find that a variable outside the function global cannot be output correctly in some cases ( That is, the global variable is invalid). Let's look at a simple and common example.

Here, we have two pages a.php and b.php. The

b.php page code is as follows:

<?php
$site_name = &#39;CodePlayer&#39;;

function sayHi(){
    global $site_name;
    echo "Hello! Welcome to $site_name !";
}
?>
Copy after login

a.php page code is as follows:

<?php

function include_view_page(){
    include &#39;b.php&#39;;
    sayHi();                    
}

include_view_page();
?>
Copy after login

The above example is very simple. We hope that when we visit the a.php page, the welcome can be displayed correctly statement. However, unfortunately, when we use the browser to access the a.php page, we find the following output:

Hello! Welcome to !
Copy after login

That is to say, we call it in the function include_view_page() When using the sayHi() function, the $site_name in the global function of the b.php page was not correctly recognized and took effect. What exactly is this matter about?

Actually, when we

include b.php page in function include_view_page(), the variable $site_name of b.php page is equivalent to the function stored in include_view_page() in the domain. As we all know, a variable within a function global actually establishes a reference to the global variable of the page within the function. In our example, this $site_name variable is just a local variable within the include_view_page() function for a.php, so it cannot be global. Naturally, we cannot get it when we make related calls. Correct variables and variable values.

In PHP, we especially need to pay attention to the above-mentioned problem of

include a certain page within a function, causing the scope of the variables in the page to change. In order to avoid this situation, we should try to reduce multiple levels of include calls and try not to use include within functions.

This failure is caused by many reasons. An effective solution is to use the $GLOBALSarray which is always valid:

$GLOBALS['site_name'] = 'CodePlayer';
Copy after login

Reference: http://www.365mini.com/page/php-global-invalid.htm

The above introduces the invalid php global variables, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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