search
HomeBackend DevelopmentPHP TutorialAbout global issues in PHP

Good afternoon everyone, I saw this knowledge point on the Internet:
global variables declared inside a function can be accessed by the external main program

Then I ran the following code and verified the above conclusion:

<code><?php function test_global() {
    global $vars;
    $vars='OK';  
}
 
test_global();  
echo $vars;      //OK
?>
</code>

Based on the above theory, I wrote the following code:

<code><?php $var1 = 1; 
function test(){ 
    global $var1;                       
    unset($GLOBALS['var1']);           
    echo $var1;
} 
test(); 
echo $var1;
?>
</code>

Global $var1 in the test function is a reference to the external variable $var1, unset($GLOBALS['var1']); causes the external $var1 to disconnect from the memory (the variable $var1 is destroyed)

Then here comes the question
According to the theory at the beginning of the question, even if the external $var1 is unset, the $var1 inside the function can still be accessed from outside the function? ($var1 in the function is also global!), but why does echo $var1 report an error in the end?
Please give me some advice, thank you!

In addition, I have another question. I hope someone can help me.
https://segmentfault.com/q/10...

Reply content:

Good afternoon everyone, I saw this knowledge point on the Internet:
global variables declared inside a function can be accessed by the external main program

Then I ran the following code and verified the above conclusion:

<code><?php function test_global() {
    global $vars;
    $vars='OK';  
}
 
test_global();  
echo $vars;      //OK
?>
</code>

Based on the above theory, I wrote the following code:

<code><?php $var1 = 1; 
function test(){ 
    global $var1;                       
    unset($GLOBALS['var1']);           
    echo $var1;
} 
test(); 
echo $var1;
?>
</code>

Global $var1 in the test function is a reference to the external variable $var1, unset($GLOBALS['var1']); causes the external $var1 to disconnect from the memory (the variable $var1 is destroyed)

Then here comes the question
According to the theory at the beginning of the question, even if the external $var1 is unset, the $var1 inside the function can still be accessed from outside the function? ($var1 in the function is also global!), but why does echo $var1 report an error in the end?
Please give me some advice, thank you!

In addition, I have another question. I hope someone can help me.
https://segmentfault.com/q/10...

It can be understood like this: global $var1; is equal to $var1=&$GLOBALS['var1'];

<code><?php $var1 = 1; 
function test(){ 
    global $var1;                       
    unset($GLOBALS['var1']);           
    echo $var1;
} 
test(); 
echo $var1;
?></code>

You can compare the running results of the upper and lower sections

<code><?php $var1 = 1; 
function test(){ 
    global $var1;                       
    unset($var1);
    echo $var1;
} 
test(); 
echo $var1;
?></code>

Let me add a paragraph too

<code><?php //#1全局的时候$GLOBALS['var']就是$var。
$var=999;
unset($GLOBALS['var']);
var_dump($var); //报错 NULL


//#2在函数内部,$GLOBALS['var']就是外部全局的$var
$var=999;
function test(){
    unset($GLOBALS['var']);
}
test();
var_dump($GLOBALS['var']); //报错 NULL
var_dump($var); //报错 NULL


//#3没有全局$var的时候,函数内部执行global $var;会创建一个空值的内部$var和一个空值的外部$var,在链接起来。
function test2(){
    global $var;
    var_dump($var); //NULL
    var_dump($GLOBALS['var']); //NULL
    $var = 999;
}
test2();
var_dump($var); //999
var_dump($GLOBALS['var']); //999</code></code>

What you declare is a global variable. Because it is global, you can delete it inside or outside the function.
After deletion, it no longer exists whether you are inside or outside the function.

Note:
The variables inside and outside the function are the same and point to the same pointer.

After declaring a global variable, it does not create a variable inside the function and a variable outside the function.

Addition:
My understanding is wrong, what @Mi Mo
downstairs said:

<code>global $var1;等于$var1=&$GLOBALS['var1'];
</code>

is correct.

Just to add:
I just realized that I didn’t see it clearly before:

<code>global $var1;等于$var1=&$GLOBALS['var1'];
</code>

This sentence is correct, but I didn’t notice the existence of & before.
Because it seems easier to understand if you remove the &.
But in fact & exists, so it’s still the same as what I said above: $var1 inside and outside points to the same address.

Let’s look back at the example:

<code>$var1 = 1; 
function test(){ 
    global $var1;                       
    unset($GLOBALS['var1']);
    echo $var1;
} 
test(); //1 已经删除了$var1,为什么函数内的$var1还存在呢?
echo $var1;//Undefined</code>

-->Question: Since they are the same thing, why does one have output and the other report an error?

Try another one:
$var1 = 1;
function test(){

<code>global $var1;                       
$GLOBALS['var1']=99;
echo $var1;</code>

}
test(); //99
echo $var1;//99

-->If you change one, the other will also change at the same time, which means they should still be the same thing, right?

So, what’s the problem?
In fact, the problem lies in the unset() function:

When you unset a reference, you just break the binding between the variable name and the variable content. This does not mean that the variable contents are destroyed.

(Reference: http://blog.csdn.net/ebw123/a...)

I have found a preliminary clue now, look at the code below:

Example 1

<code><?php function test(){            
    global $var;                       
    $var=999;
}
test(); 
echo $var;                //999
?></code>

Example 2

<code><?php function test(){            
    global $var;
    unset($GLOBALS['var']);                        
    $var=999;
}
test(); 
echo $var;                //错误
?>
</code>

Example 3

<code>    <?php function test(){   
        unset($GLOBALS['var']);           
        global $var;              
        $var=999;
    }
    test(); 
    echo $var;                //999
    ?>
</code>

Based on the question and the code in this reply, the summary is as follows
Use unset($GLOBALS['var']) within the function;

1: It will destroy the $var variable outside the function (because $GLOBALS[ 'var'] is the outer $var itself)

2:

  • If there is a global variable (can be accessed externally) before unset($GLOBALS['var']); inside the function, then unset($GLOBALS['var']); will cancel the external access to the global variable in the function "right"

  • Inside the function, if there is already a global variable (can be accessed externally) after unset($GLOBALS['var']);, then unset($GLOBALS['var']); will not interfere with external access inside the function "Rights" of global variables

Question:
In addition to unset($GLOBALS['var']); you can destroy the external variable $var to reduce the refcount of the zval it points to by one,

Could it also change the scope of global variables originally within a function from global to local (causing global variables inside the function to be inaccessible from the outside)?

Hope, God can give me some guidance.

Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor