search
HomeBackend DevelopmentPHP TutorialPHP variables for PHP learning_PHP tutorial

PHP variables for PHP learning_PHP tutorial

Jul 21, 2016 pm 04:05 PM
phponeunderhostinternalvariablestudysupportintegeroftype

PHP variables

PHP3 supports the following types of variables:
(1), internal variables
Mainly include integers (interger), floating-point numbers (float-point numbers), strings (string), and arrays (array), object (object).
1 Initialize variables
To initialize a variable in PHP, you simply assign a value to it. For most types, this is the most straightforward. For arrays and objects, other methods are available.
2 Initializing the Array
Arrays can be assigned using one of two methods: using a series of consecutive values, or constructing them using the array() function (see the Array functions section).
To add consecutive values ​​to an array, you only need to assign the value to the array variable without a subscript. This value will be added to the array as the last element of the array.
Example:   $names[] = "Jill"; // $names[0] = "Jill"   $names[] = "Jack"; // $names[1] = "Jack" Similar to c and perl ,
Array subscripts also start from 0.
3 Initialize object
To initialize an object, you need to use the new statement to create a variable of this type.
class foo {       
function do_foo() {      
echo "Doing foo."; variable scope
The scope of a variable is its effective scope. For most PHP variables there is only one scope. Use local variable scope in user-defined functions.
Variables used within functions are set to local variables by default. For example:   Something, because the echo statement wants to output the local variable $a, and $a within the function has never been assigned a value.
You may notice that this is a little different from the C language. In C, global variables can be directly referenced within the function unless it is overwritten by a local variable.
This makes it possible for people to modify the value of global variables without noticing. In PHP, global variables must be used explicitly within a function.
For example:    $a=1;   $b=2;    Function Sum() {     global $a,$b;        $b = $a + $b; echo $b; above program will output "3".
By declaring $a and $b as global variables inside the function, all required variables refer to the global world. There is no limit to the number of global variables that a function can manipulate.
Another noteworthy aspect of scope is the static variable.
A static variable exists in a local function, but its value is not lost when the program leaves the function.
Consider the following example: Function Test() { $a=0; echo $a; $a++; }
This function is useless because it first sets $a to 0 every time it is called Then type "0". The self-increment of $a++ has no effect because the variable
$a is released after the function call ends. To make the counting program count effectively without losing the current counting result, $a must be declared as a static variable:
Function Test() { static $a=0; echo $a; $a++;
} Now, every time the Test() function is called it will print the value of $a and increment it. Static variables are essential when using recursive functions.
A recursive function is a function that calls itself. Be very careful when writing recursive functions,
because the number of loops is uncertain. You must ensure that there are sufficient conditions to end the recursive process. Here is a simple recursive function to count to 10:
Function Test() { static $count=0; $count++;
echo $count; if($count (2) For dynamic variables, it is sometimes more convenient to use variable variable names. That is, a variable name that can be dynamically assigned and used.
The assignment statement of an ordinary variable is such as:   $a = "hello";   A dynamic variable refers to the value of the variable as the name of a new variable.
In the above example, hello can be used as a variable name by double $.
Example:   $$a = "world"; At this point, two variables are defined and stored in the PHP symbol tree: the content of $a is "hello", and the content of $hello is "world".
Therefore, the display result of the statement: echo "$a ${$a}"; is exactly the same as: echo "$a $hello"; (3) PHP external variables 1, HTML form (GET and POST)
When a form is submitted to PHP3 script, PHP will automatically get the variables in the form.For example:    

   Name: 2. IMAGE SUBMIT variable name
When submitting a form, you can replace the standard submit button with an image through the following markup: When the user clicks on the image,
two additional variables sub_x and sub_y will accompany the form Send them to the server together. It contains the coordinates of where the user clicked on the graph.
Experienced people may notice that the name actually sent by the browser contains a period instead of an underscore, but PHP automatically converts the period into an underscore.
3. HTTP Cookies
PHP supports HTTP cookies. Cookies store data in the client's browser to keep in touch with the user or authenticate the user's identity.
You can use the setcookie() function to set cookies. Cookies are part of the HTTP request header, so the SetCookie() function must be called
before any output data is returned to the user's browser. It is similar to the limitation of the Header() function. Any cookies returned from the client will be automatically converted into standard PHP variables
just like data for GET and POST methods.
If you want to set multiple values ​​in a cookie, add [] to the name of the cookie,
For example:   SetCookie("MyCookie[]","Testing", time()+3600);   🎜>Note: New cookies will overwrite existing cookies with the same name in your browser unless they have different paths or domains.
4. Environment variables
PHP automatically converts environment variables into ordinary variables.
echo $HOME; /* Shows the HOME environment variable, if set. */   
Although information from GET, POST and Cookie structures will also be automatically converted into PHP variables, it is best to explicitly retrieve them from the environment Read them from variables to ensure you get the correct values.
Use the getenv() function for this. Variables can also be set via the putenv() function.
Variable type conversion
PHP does not require (and does not support) explicit type declarations when defining variables; the type of a variable depends on the type of its value.
In other words, if you assign a string value to the variable var, var becomes a string variable. If you assign an integer value to var, it becomes an integer variable.
An example of PHP’s automatic type conversion is the addition operator '+'. If any operand is of type double, all operands are calculated as type double, and the result is also of type double. Otherwise, all operands are calculated as integer types, and the result is also of integer type. Note: The type of the operand itself does not change;
Type conversion is only done during calculation $foo = "0"; // $foo is a string (ASCII 48)   $foo++; // $foo is the string " 1" (ASCII 49)
$foo += 1; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a double (3.3) $foo = 5 + "10 Little Piggies"; // $foo is a double (15) $foo = 5 + "10 Small Pigs"; // $foo is an integer (15)
To change the type of the variable, also The settype() function is available.
1. Forced type conversion
Forced type conversion in PHP is the same as in C: write the desired type name in parentheses before the variable that needs to be typed.
$foo = 10; // $foo is an integer $bar = (double) $foo; // $bar is a double
The allowed casts are: (int), (integer) - cast to integer (real), (double), (float) - cast to double
(string) - cast to string (array) - cast to array (object) - cast to object
Note: brackets can contain tabs or space, the following function will be calculated:   $foo = (int) $bar;   $foo = (int) $bar;
2. String conversion
When a string is calculated as a numeric type, the result The value and type are determined as follows.
If the string contains any '.', 'e', ​​and 'E' characters, it is calculated as a double type. Otherwise, it is calculated as an integer type.
The value is counted from the beginning of the string. If the string is a legal number, this value is used, otherwise the value is 0.
A legal number is a sign bit (optional), followed by one or more digits (can also contain a decimal point), followed by an optional exponent.
The exponent is an 'e' or 'E' followed by one or more digits. $foo = 1 + "10.5"; // $foo is a double (11.5)  
$foo = 1 + "-1.3e3"; // $foo is a double (-1299)   $foo = 1 + " bob-1.3e3"; // $foo is a double (1)  
$foo = 1 + "bob3"; // $foo is an integer (1)  $foo = 1 + "10 Small Pigs"; / / $foo is an integer (11)  
$foo = 1 + "10 Little Piggies"; // $foo is a double (11); the string contains 'e'

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/315727.htmlTechArticlePHP variables PHP3 supports the following types of variables: (1) Internal variables mainly include integers (interger) and floating point numbers. (float-point numbers), string (string), array (array), object (object). 1 Initial...
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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment