Variable scope

Содержание
Local scope
The global keyword
Static variables
Pass by value and reference

Local scope

Variables created inside a function are local: they exist only while the function runs and stay invisible outside it. An outer variable with the same name is a different variable, so the two never overwrite each other by accident.

$name = "Ada"; function show(): void { $name = "Grace"; echo $name; } show(); echo $name;

The global keyword

The global keyword imports an outer variable into the function, so reads and writes touch the shared copy. It works, but it hides the data flow: prefer parameters for input and return for output, and reserve global for small scripts and legacy code.

$total = 0; function addBonus(int $points): void { global $total; $total = $total + $points; } addBonus(5); echo $total;

Static variables

A static variable inside a function keeps its value between calls. It initializes once and then remembers, which suits counters, caches of expensive results, and one-time setup flags.

function counter(): int { static $n = 0; $n++; return $n; } echo counter(); echo counter();

Pass by value and reference

Scalar arguments pass by value: the function works with a copy, and the caller variable stays unchanged. An & before a parameter passes by reference instead, so assignments inside the function modify the caller variable directly. Use references sparingly and document them, because hidden writes surprise readers.

function bump(int &$n): void { $n++; } $x = 1; bump($x); echo $x;

Next: include and require

Автор статьи: Arthur Isaev

Похожие статьи
Программирование на PHP
PHP course: zero to hero in 50 lessons
What is PHP and where it runs
Install PHP 8.5 and run your first command
Your first PHP script
Comments in PHP
Variables and constants
Types in PHP
Strings in PHP
Numbers in PHP
Operators
if and else
switch and match
Ternary, null coalescing and nullsafe
Loops
Arrays
Associative arrays
Functions
Variable scope
include and require
Namespaces
Composer and autoloading
Everyday string functions
Dates and time
JSON in PHP
Reading and writing files
Errors: read, reproduce, fix
Classes and objects
Constructors and promotion
Inheritance
Interfaces and traits
Enums
Magic methods
Attributes
Exceptions
Strict types
Closures and arrow functions
Generators with yield
Forms: GET and POST
HTTP: headers and status codes
Cookies
Sessions
Login with sessions
JSON REST endpoint
Database with PDO
Uploads and .htaccess
Lint like a pro
Clean functions
Debugging
Modern PHP tour: 5 to 8.4
PHP 8.5 for busy developers
Hero roadmap: the whole course on one page

Поиск по сайту

Канал @aofeed Чат @aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: