Home Backend Development PHP Tutorial Introductory tutorial on php variables, basic knowledge of php variables

Introductory tutorial on php variables, basic knowledge of php variables

Jul 25, 2016 am 08:51 AM

  1. $a = 'hello';
  2. function test() {
  3. var_dump($a);
  4. }
  5. // test();
  6. include 'b.inc';
Copy code

b.inc content:

  1. echo 'hello';
  2. ?>
Copy code

The program can output hello normally, but the commented out test() cannot be parsed normally because of the variable $a is undefined.

4. Use global variables If you want to use global variables in a function, you can use the following two methods.

global keyword global $a, $b; When a global variable is declared in a function, all references to any variable point to its global version.

$GLOBALS super global variable array $GLOBALS['b'] = $GLOBALS['a'] + $BLOBALS['b']; Usage is similar to the global keyword.

5. Static variables Static variables only exist in the local function scope, but their values ​​are not lost when program execution leaves this scope. Moreover, it is only initialized once when it is declared, and the value of the static function will not be overwritten each time the function is called.

Assigning a static variable with the result of an expression in the declaration will cause a parsing error. Static declarations are parsed at compile time.

  1. function test() {
  2. static $cnt = 0;
  3. echo $cnt;
  4. $cnt++;
  5. if($cnt < 10) {
  6. test();
  7. }
  8. $cnt--;
  9. }
  10. test();
Copy code

is similar to static in C language. The following C code can also output ten numbers from 0 to 9 in sequence.

  1. #include
  2. void test(void) {
  3. static int cnt = 0;
  4. printf("%d ", cnt);
  5. cnt++;
  6. if(cnt < 10) {
  7. test();
  8. }
  9. cnt--;
  10. }
  11. int main(void) {
  12. test();
  13. return 0;
  14. }
Copy code

The static and global definitions of variables are Implemented by reference.

5. Variable variables Variable variables are a special usage in PHP language. I don’t know if they exist in other languages.

In short, a variable variable means that a variable variable obtains the value of an ordinary variable as the variable name of the variable variable.

  1. $a = 'hello';
  2. $$a = 'world';
  3. echo "$a $$a"; // hello $hello
  4. echo "$a ${$ a}"; // hello world
Copy code

When mutable variables are used in arrays, ambiguity may arise. For example, if you write $$a[1], the compiler will report an error. The meaning you want to express needs to be replaced in the following two ways.

${$a[1]} $a[1] as a variable

${$a}[1] $$a acts as a variable and takes out the value with index 1 in the variable.

6. Form variables When a form is submitted to a PHP script, the information in the form is automatically available in the script and can be accessed via $_GET[], $_POST[] and $_REQUEST[].

Note that dots and spaces in variable names are converted to underscores. For example, becomes $_REQUEST["a_b"]. The following example shows the use of identifiers in the form.

Copy code

form Process file process.php.

  1. var_dump(isset($_POST['my.text']));
  2. var_dump(isset($_POST['mytext']));
  3. var_dump(isset($_POST[ 'my_text']));
  4. var_dump($_POST['my_text']);
Copy code

Because the period is not a legal character in PHP variable names, the output result is: boolean false boolean false boolean true

string 'h3' (length=2) The magic_quotes_gpc configuration directive affects the value of get/post/cooie. This feature has been deprecated and removed. Single quotes, double quotes, backslashes and NULL characters in the input will not be escaped. If you need to escape, you can use addslashes(). If you need to dequote a quoted string, you need to use stripslashes().

php also understands arrays in form variable context.

Example, use more complex form variables and post the form to yourself and display the data on submission.

  1. if(isset($_POST['action'])) {
  2. var_dump($_POST);
  3. } else {
  4. $page = $_SERVER['PHP_SELF'];
  5. $ s = <<
  6. STR;
  7. echo $s;
  8. }
Copy code

Be extra careful when containing complex variables in the heredoc. The above code $_SERVER['PHP_SELF'] without curly brackets will cause an error when running.

  1. if(isset($_POST['action'])) {
  2. var_dump($_POST);
  3. } else {
  4. $s = <<< form action="{$_SERVER['PHP_SELF']}" method="post">
  5. STR;
  6. echo $s;
  7. }
Copy code

For the above program, when the user clicks on the picture At some point, the form will be sent to the server, and two variables sub_x and sub_y will be added, containing the coordinates of the user's clicked image.

array (size=3) 'action' => string '1' (length=1) 'sub_x' => string '334' (length=3) 'sub_y' => string '282' (length=3) cookies

php can set cookies with the setcookie() function. Cookies are part of the http information header, so they must be called before sending any output to the browser.

php cookies use:

Cookie data is available in the corresponding cookie array. If multiple values ​​are assigned to a cookie variable, they must be assigned to an array.


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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles