Using global variables in function php

PHP Global: глобальные переменные

В этой статье пойдет разговор о том, что такое глобальные переменные в PHP и чем они отличаются от локальных. Также читатель узнает о том, как использовать ассоциативный массив $GLOBALS вместо ключевого слова Global. Пояснения будут даны на конкретных примерах.

В языке программирования PHP существует понятие глобальных переменных (globally variables). Но для начала следует вспомнить о переменных локальных. Последние определены внутри пользовательской функции (внутри подпрограммы), причем на нее вы сможете ссылаться лишь в этой функции. Таким образом, локальная variable доступна лишь внутри той функции, в которой она определена (доступна в локальной области видимости).

Глобальные значения, в отличие от локальных, доступны всей программе целиком, куда также входят и подпрограммы (пользовательские функции).

Для языка программирования PHP все переменные, которые объявлены и задействуются в функции, локальны для функции (так обстоят дела по умолчанию). Таким образом, по дефолту возможность поменять значение переменной global в теле функции отсутствует.

Давайте представим, что мы в теле пользовательской функции PHP захотим применить переменную с именем, причем это имя будет идентично имени глобальной переменной, которая находится вне user function. В результате никакого отношения данная локальная variable к глобальной иметь не будет. В описанном только что случае в пользовательской функции будет создана local variable, причем с именем в PHP, которое будет идентично имени global variable, однако доступна такая переменная будет лишь внутри нашей пользовательской функции.

Все вышеописанное лучше пояснить на примере:

Сценарий кода выведет сначала 555, а потом 888. Чтобы избавиться от недостатка, продемонстрированного в function test (это не ошибка, а именно недостаток), в языке программирования PHP предусмотрена особая инструкция global. Эта инструкция дает возможность пользовательской функции взаимодействовать с глобальными переменными.

Рассмотрим этот принцип на очередном примере:

Скрипт с function sum выведет результат 15. Что тут произошло? После того, как $x и $y были определены внутри нашей функции в качестве global, все существующие ссылки на любую из этих статических переменных стали указывать уже на их глобальную версию. При данных обстоятельствах отсутствуют какие-либо ограничения на количество global variables, доступных к обработке с помощью user functions.

Читайте также:  Php listing directory contents

PHP и глобальные переменные. Массив $GLOBALS

Есть и другой способ, обеспечивающий доступ к глобальной области видимости. Он заключается в применении специального массива , определяемого PHP. Мы можем переписать предыдущий пример иначе, задействовав $GLOBALS:

$GLOBALS[«y»] = $GLOBALS[«x»] + $GLOBALS[«y»];

$GLOBALS является ассоциативным массивом, его ключ — это имя, его значение — это содержимое глобальной переменной. Важно обратить внимание на тот факт, что $GLOBALS может существовать практически в любой области видимости, что объясняется следующим образом: данный массив является суперглобальным.

Ниже расположен пример, который демонстрирует возможности использования суперглобальных переменных:

Хотите знать о PHP гораздо больше? Добро пожаловать на курс!

Источник

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

Example

Variable with global scope:

function myTest() // using x inside this function will generate an error
echo «

Variable x inside function is: $x

«;
>
myTest();

echo «

Variable x outside function is: $x

«;
?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

Example

Variable with local scope:

function myTest() $x = 5; // local scope
echo «

Variable x inside function is: $x

«;
>
myTest();

// using x outside the function will generate an error
echo «

Variable x outside function is: $x

«;
?>

You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

PHP The global Keyword

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example

function myTest() global $x, $y;
$y = $x + $y;
>

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index] . The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.

The example above can be rewritten like this:

Читайте также:  Выравнивание ячеек таблиц html

Example

function myTest() $GLOBALS[‘y’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
>

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Note: The variable is still local to the function.

Источник

How to declare global variables in PHP

Posted on Aug 11, 2022

PHP global variables refer to any variables you declared outside of a function.

Here’s an example of declaring a global variable in PHP:

   PHP global variables are directly accessible from any part of the PHP script as long as it’s outside of a function .

For example, suppose you split the code above into two PHP files related using the include keyword:

    "; The b.php script can still access the $first_name and $last_name variables as long as you include or require the script as shown above.

Access PHP global variables from a function

Global variables are not directly available inside a PHP function.

When you access a global variable from a function, the undefined variable warning will appear:

Let’s learn about these methods next.

Access PHP global variables using the global keyword

The global keyword is used to reference variables from the global scope inside PHP functions.

Here’s an example of using the global keyword:

 In the code above, the $name is declared global inside the function, so the $name from outside of the function is imported into the function.

The global keyword points to the global variable without copying the value.

When you change the $name value inside the function, the actual $name value will change as well:

  Keep this in mind when you’re accessing the variable from many functions, as the variable may have been changed when you access it.

To access global variables from many functions, you can use the global keyword in each function as follows:

But as you can see, the code becomes quite repetitive.

To avoid having to declare global in each function, you can use the $GLOBALS variable instead.

Access PHP global variables using the $GLOBALS array

The $GLOBALS is an associative array containing references to all global variables available in your PHP script.

You can access the global variables by passing the variable name as the array key like this:

Using the $GLOBALS array is more convenient when you need to access the global variable from many functions.

You don’t need to refer to the variable using the import keyword in each function:

When you modify the $GLOBALS element, the actual variable value will be changed as well:

And that’s how you access the global variables using the $GLOBALS array.

Should you use global variables in PHP?

Global variables can reduce the amount of code you need to write, but it’s also considered bad practice because it’s harder to debug your code when something goes wrong.

When you’re accessing a variable local to the function, you can easily check the function to see if you did something wrong with it.

But if the variable is global, you need to check all the lines where you call that variable and see if the code goes wrong in one of the lines.

To conclude, you are free to use global variables in PHP when it helps. But you also need to consider the difficulty in maintaining and debugging global variables in a complex web application.

I hope this tutorial has been useful for you 🙏

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

Оцените статью