search
HomeBackend DevelopmentPHP TutorialDetailed explanation of php variables, php variables_PHP tutorial

Detailed explanation of php variables, php variables

Variables are "containers" used to store information.

Syntax for defining a variable:

$变量名 = 值;

Example of using variables:

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

Run

As you can see from this example, the variable name starts with $, indicating that it is a variable. Variable names start with letters (a-z, A-Z) or underscores _, and can be followed by any letters or numbers and underscores, but not spaces.

PHP variable rules:

  • Variables start with a $ symbol followed by the name of the variable
  • Variable names must start with a letter or underscore character
  • Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
  • Variable names cannot contain spaces
  • Variable names are case-sensitive ($y and $Y are two different variables)

Note: PHP statements and PHP variables are case-sensitive.

The following variable names are valid:

$var_char
$varChar
$_varChar
$var_char5

Create (declare) PHP variables

PHP has no command to declare variables.

A variable is created the first time you assign a value to it:

<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>

In the execution of the above statement, the variable txt will save the value Hello world!, and the variable x will save the value 5 .

Note: When you assign a text value to a variable, please put quotation marks around the text value.

PHP is a weakly typed language

In the above example, we noticed that it is not necessary to declare the data type of the variable to PHP.

PHP will automatically convert the variable into the correct data type based on its value.

In a strongly typed programming language, we must declare (define) the type and name of the variable before using it.

PHP variable scope

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

PHP has four different variable scopes:

  • local
  • global
  • static
  • parameter

Local and global scope

Variables defined outside all functions have global scope. In addition to functions, global variables can be accessed by any part of the script. To access a global variable in a function, you need to use the global keyword.

Variables declared inside a PHP function are local variables and can only be accessed inside the function:

<?php
$x=5; // 全局变量
function myTest()
{
$y=10; // 局部变量
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
} 
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>

In the above example, the myTest() function defines $x and $y variables. The $x variable is declared outside the function, so it is a global variable, and the $y variable is declared inside the function, so it is a local variable.

When we call the myTest() function and output the values ​​​​of two variables, the function will output the value of the local variable $y, but cannot output the value of $x, because the $x variable is defined outside the function and cannot be inside the function Use, if you want to access a global variable in a function, you need to use the global keyword.

Then we output the values ​​of the two variables outside the myTest() function. The function will output the value of all local variables $x, but cannot output the value of $y, because the $y variable is defined in the function and is a local variable. .

Note: You can use the same variable name in different functions, because the variable names defined in these functions are local variables and only affect that function.

PHP global keyword

The global keyword is used to access global variables within a function.

To call a global variable defined outside the function within a function, we need to add the global keyword before the variable in the function:

<?php
$x=5;
$y=10;
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // 输出 15
?>

PHP stores all global variables in an array called $GLOBALS[index]. index saves the name of the variable. This array can be accessed inside the function or used directly to update global variables.

The above example can be written like this:

<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
} 
myTest();
echo $y;
?>

Static scope

When a function completes, all of its variables are usually deleted. However, sometimes you want a local variable not to be deleted.

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

<?php

function myTest()
{
static $x=0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

?>

Then, each time the function is called, the variable will retain the value from the previous time the function was called.

Note: The variable is still local to the function.

Parameter scope

Parameters are local variables whose values ​​are passed to the function through the calling code.

Parameters are declared in the parameter list, as part of the function declaration:

<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>

Original address: http://www.manongjc.com/php/php_variables.html

php related reading:

php str_pad() function completes the string to the specified length

Analysis and explanation of usage of php str_replace() string replacement function

php str_ireplace() function is case-insensitive to replace characters in a string

php str_getcsv() function parses the CSV string into an array

php sscanf() function usage and examples

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1128379.htmlTechArticleDetailed explanation of php variables. PHP variables Variables are "containers" used to store information. The syntax for defining a variable: $Variable name = value; Example of using variables: ?php$x=5;$y=6;$z=$x $y;echo $z;?...
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor