What is the usage of global in php?

coldplay.xixi
Release: 2023-03-03 10:46:02
Original
4016 people have browsed it

The usage of global in php is: 1. If you use global to declare, you can call variables outside the function; 2. Introduce the [$mk] variable outside the function, and global will be globalized here. The meaning of the variable.

What is the usage of global in php?

The usage of global in php is:

To introduce a variable in java, it can be passed in the form of parameters , because Java uses object-oriented programming, but there are a lot of process-oriented things in PHP. For example, when an external variable is introduced into a function, under normal circumstances, this external variable is not passed in through parameters. , but introduced directly through global. But this global does not mean globalization. It is a test of the code.

$mk ="Test value"; 
function initValue()
{
$va =$mk;
echo $va;
}

Copy after login

The running result is:

- Undefined variable: mk
Copy after login

Because$mkis only defined in the method , so it is a different variable from$mkdefined before the method.$mkhas no value assigned, so an error is reported.

If it is declared with global, you can call variables outside the function.

$mk ="Test value"; 
function initValue()
{
global $mk;
$va =$mk;
echo $va;
}
initValue();
Copy after login

The running result is: Test value. Here, global is used to introduce the$mkvariable outside the function.

In order to test global, here There is no meaning of globalizing variables, so I did another test.

$mk ="Test value"; 
function initValue()
{
global $mk;
$va =$mk;
echo $va;
}
function initValue2()
{
$vc =$mk;
echo $vc;
}
initValue();
initValue2();
Copy after login

The running results are: Test value and - Undefined variable: mk, which shows that even if global is used, it is only valid in a function, so the global here is just to introduce the upper variable

Related learning recommendations:PHP programming from entry to proficiency

The above is the detailed content of What is the usage of global in php?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!