[Introduction to php basics] Detail php variables and constant points of knowledge

Posted by aspbyte on Fri, 18 Feb 2022 22:49:57 +0100

Foreword: mix one day and work hard one day, one day does not see any difference, three days do not see any change, seven days do not see any distance... But after one month you will see different topics, after three months you will see different atmosphere, after six months you will see different distances, after one year you will see different paths in life.

1. Detailed explanation of PHP variables

Variables are containers that temporarily store values, such as numbers, text, or some complex data. The value of a variable changes at any time when the program is running. It gives a short, easy-to-remember name to a piece of data that is ready for use in the program. It also saves data entered by the user or the result of an operation.

1.1 Output Statement

In PHP, echo, print, print_can be used R, printf, sprintf, var_ There are six dump statements to implement the output.

  1. echo statement
    echo() is not really a function, it is a php statement, so you don't need to use parentheses for it. However, if you want to pass more than one parameter to echo (), there will be parsing errors using parentheses. Echo also returns void and does not return a value, so it cannot be used for assignment.
<?php
echo "words";  

echo ("words"); 

echo ("apple","bear"); //Error, parentheses cannot pass multiple parameters

echo "alice","bill","cart", "daring";  // When parentheses are not used, multiple values can be separated by commas, and alicebillcartdaring will be output with or without a line break

$fistname="alice";
echo "$fistname com"; // If $firstname = "alice", alice com is output.

echo '$firstname com'; // Since single quotation marks are used, instead of outputting the value of $firstname, output $firstname com

// Note here that you will learn later that single quotation marks do not resolve variables

$a = echo("words"); // Error! Cannot be used for assignment
?>

Note: Normally, the output of echo or echo() is the same. Parsing errors are generated using parentheses only when multiple parameters are passed to the echo statement for output.

  1. print statement
    print() is used the same as echo(), but echo will be a little faster than print. It's not actually a function, so you don't need to use parentheses. The print statement also implements output with a return value. When the output succeeds it returns 1 and failures it returns 0. So it can be used in expressions.
<?php
print "hello ";

print ("world!");

echo print "hello";
?>
  1. printf() function
    The printf() function can also output a normal string or format the output string. Example:
<?php
// Pritf (Format Template, Data...)
$a=20;
$b=30;
printf("Output: a=%d,b=%d,%1\$d+%2\$d=%d",$a,$b,$a+$b); // Output: a=20,b=30,20+30=50

printf("My name is %s %s. ","alice", "com"); // My name is alice com. 
printf("My name is %1\$s %1\$s","alice", "com"); // Add 1$or 2$... before s. Indicates the position of the last parameter to be displayed, and this line outputs My name is alice alice because only the first parameter is displayed twice.
printf("My name is %2\$s %1\$s","alice", "com"); // My name is com alice
?>
  • %%- Returns the percentage symbol
  • %b - Binary Number
  • %c - Characters based on ASCII values
  • %d - Signed Decimal Number
  • %e - Scientific Counting (e.g. 1.5e+3)
  • %u - Unsigned Decimal Number
  • %f - Floating Point (local settings aware)
  • %o - Octal Number
  • %s - String
  • %x - Hexadecimal Number (%x Lowercase Letter%X Uppercase Letter)
  1. sprintf function
    The only difference between this function and printf is that it writes formatted strings to a variable instead of outputting them. (Instead of typing, he returns the formatted string)
<?php 
// Sometimes we just want to save the formatted string instead of printing it out
// sprintf() is used at this point
// pdo:dsn,'mysql:host=localhost;dbname=phpedu;'
$type = 'mysql';
$host = 'localhost';
$dbname = 'phpedu';
$linkParams = [$type,$host,$dbname];
// Direct Format Output
printf('%s:host=%s;dbname=%s;',$type,$host,$dbname);
// vprintf() supports array parameters
vprintf('%s:host=%s;dbname=%s;',$linkParams); // mysql:host=localhost;dbname=phpedu;
// Return formatted string directly without output
$dsn = sprintf('%s:host=%s;dbname=%s;',$type,$host,$dbname);
$dsn = vsprintf('%s:host=%s;dbname=%s;',$linkParams);
echo $dsn;
?>
  1. print_r-function
    Print_ The r() function is used to output a variable, and information about the variable can be displayed in a format that is easily readable by humans.

print_r has two parameters, the first is a variable, the second can be set to true, and if set to true, the string will be returned, otherwise the Boolean value TRUE will be returned.

<?php

$a="alice";

$c = print_r($a); // Print alice returns Boolean true
echo $c;  // The value of $c is TRUE

// The second parameter, set to true, converts the variable's information into a string that is not exported to the browser for online debugging, sql logging
$c = print_r($a,true); // Do not print, return string content
echo $c; // The value of $c is the string alice


$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z'));

echo "</pre>";
print_r ($a);
echo "</pre>";
?>

  1. var_dump() function
    Var_ The dump() function is used to output the content, type, and length of a variable and can display structured information about the variable, such as type, value. Code debugging is commonly used during development.
<?php
$var_name=array(99,'w3resource',67899.99, array('X','Y',1));

var_dump($var_name);

    $passed = true;
    // Direct echo let converts Boolean values to string output of 1
    echo $passed;  // 1
    // Print Actual Value
    echo var_export($passed,true); // true
    // Print type
    echo gettype($passed); // boolean
    echo gettype(gettype($passed)); // string
    // var_dump() can print both values and types
    var_dump($passed);
?>

Output summary:

  • echo can output numeric and character types. When output boolean, true output is 1, false output is empty
  • Pritf can output numeric, character, Boolean types. When Boolean is output, true outputs 1 and false outputs 0.
  • print_r can output numbers, characters, Booleans, and arrays. When output Boolean type, true output results are 1, false output results are empty; The output array is in the form of'key'=>'value'.
  • var_dump() determines the type and length of a variable and outputs the value of the variable, if a variable has a value, it enters the value of the variable and returns the data type. This function displays structural information about one or more expressions, including the type and value of the expression. Arrays expand values recursively and show their structure by indentation.
  • Die() has two functions: it outputs the content first, then exits the program. Generally used for judging database connections, once die() is executed, the following will not be executed.
    mysql_connect('locahost','root','root') or die('link server failed!');

ob_clean() is a built-in function that empties the contents of the output buffer
file_put_contents('log.text', $res); Function writes a string to a file

<?php
//The following output hello will be added to the cache
echo 'hello';
//Empty the contents of the cache, the hello above will not output again
ob_clean();
echo "world!";

$arr = ["id"=>1,"name"=>"zhang","gender"=>"man",age=>18];
$res = print_r($arr,true);
file_put_contents('log.text','Write Array Information'.$res);
echo "<pre>".print_r($arr,true)."</pre>";
?>

1.2 Data Types

The data types in PHP can be divided into three categories: scalar data type, composite data type, and special data type.

typemember
Basic typesBoolean, String, Numeric (Integer and Floating Point)
Composite typeArray, Object
Special Typesnull, resource, callback, closure

1.Four basic types

  • integer
  • Floating Point Number (float)
  • boolean
  • string
typefunction
stringStrings are sequential sequences of characters
integerAn integer contains all integers, either positive or negative.
floatFloating-point type is used to represent decimals and exponents in addition to integers
booleanBoolean
<?php
    //Double quotation mark declaration string
    $str1 = "PHP Study";  
    //Single quotation mark declaration string
    $str2 = 'output hello world!';    
    // Stitching of strings (using dots. stitching strings)
    echo $str1.$str2; // PHP learning output hello world!

    // When a string contains double or single quotes that conflict with delimiters
    // We can change the delimiter to a single quotation mark
    echo 'Hello. zhang"!'; // Hello "zhang"!
    // Use quotation marks to escape characters
    echo "Hello\"zhang\"!"; // Hello "zhang"!
    echo "C:\\web\\table\\index.html";
    // Note: Single quotation marks recognize only two escape characters \, \
    // Single double quotation mark differences: character transfer, variable parsing, run speed.

    // Define a variable of an integer data type
    $x = 5985;    
    // Output this variable    
    var_dump($x);  // int(5985)
    // Octal Hexadecimal Binary
    var_dump(0745,0x5ac,0b11011); // int(485) int(1452) int(27)
    // Define a floating-point variable
    $num1 = 3.1415926; 
     var_dump($num1); // float(3.1415926)
     var_dump(5.6e3); // float(5600) scientific calculation method

     // Define a variable whose Boolean type is false
    $y = faLse;
    var_dump($y); // bool(false)

	// Scalar Type
	 $int = 18;
     $float = 18.88;
     $bool = false;
     $str = 'hello world!';
?>

2. Two Composite Types

  • array
  • object

An array is a collection of data that is organized into a set of rules. The essence of an array is to store, manage, and manipulate a set of variables. Arrays can be one-dimensional, two-dimensional, and multidimensional in terms of their dimensions. We can use the array() function to create an array.

// Array array (key) =>value, key =>value,...)
// Default index 0 1 2 3 (index array)
$arr1 = [12,13,18,62,85];

// The key to the specified array is also the index. Similar to object literals in js (associated arrays)
$arr2 = ["id"=>1,"name"=>"zhang","age"=>18,"gender"=>'man'];
$user = array("id"=>1,"name"=>"zhang","age"=>18,"gender"=>'man');

var_dump($arr1,$arr2);
// array(5) { [0]=> int(12) [1]=> int(13) [2]=> int(18) [3]=> int(62) [4]=> int(85) } 
// array(3) { ["id"]=> int(1) ["name"]=> string(5) "zhang" ["age"]=> int(18) ["gender"]=> string(man) }


$arr = array('a','b','c','d','e');
// Add an item at the end
$arr[] = "f";
// Print Array
vprintf('Array ( [0] => %s [1] => %s [2] => %s [3] => %s [4] => %s [5] => %s ) ',$arr);
// Use the same output effect for printing arrays
print_r($arr);  // Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f ) 

echo $arr[0],'<br >';  // a
echo $arr[1],'<br >';  // b
echo $arr[5],'<br >';  // f

// Traversing through index arrays
for($i=0;$i<count($arr);$i++) {
    echo $arr[$i],'<br >';
}

// foreach is designed to loop arrays
foreach ($variable as $key => $value) {
    # code...
}
// The variable name ($k,$v) of the key value in foreach is any valid variable name
$arr = array('name'=>'zhangsan' , 'age'=>24 , 'area'=>'Beijing');
foreach($arr as $k=>$v) {
    echo $k,':',$v,'<br >';
}
// Note: We can omit keys, print values only, but not keys only
// array_keys - Returns all key names in the array
print_r(array_keys(arr2)); // Returns an array of key names

Objects can be used to store data. Objects must be declared in PHP. Class objects must first be declared using the class keyword. A class is a structure that can contain attributes and methods. The data type is then defined in the class and used in the instantiated class.

In object-oriented languages, you can abstract the common features and behaviors of individual objects into an entity, called a "class", which is the result of instantiating a class using the new keyword.

class Car  //Declare a class object using class
    {
        private $color; // Variable="attribute
        // Function= method
        public function setCar($color="black") {
            // $this represents the current object
            $this->color = $color;
        }
        public function getColor() {
            return $this->color;
        }
    }
    $car1 = new Car();  // Instantiate Object
    // Instantiate Name - > Member Attribute Method
    $car1->setCar('red'); // Set the value red for $color
    echo $car1->getColor(); // Get the value red of $color

    $car2 = new Car();
    $car2->setCar();
    echo $car2->getColor(); // black

3. Two special types

  • Null NULL
  • Resources
// NULL is a special data type in PHP. It has only one value, NULL, which means null value (variable has no value). It is important to note that NULL has a different meaning from space.
// He does not represent spaces, empty strings, zero, null case insensitive NULL
$str = NULL;
var_dump($str);
$username = 'zhang';
unset($username); // Release Variable
@var_dump($username); // @Error Suppressor

// (resource) A reference to a resource type saved to an external resource
// fopen()
header("content-type:text/html;charset=utf-8");//Set up encoding to solve Chinese random code
$file = fopen("log.txt", "rw");//Open test.txt file
var_dump($file); // resource(3) of type (stream) 3 is the resource type id stream resource type

// imagecreate()
$image_handle = imagecreate(100,50);
var_dump($image_handle); // resource(2) of type (gd)

1.3 Data Type Conversion

PHP data type conversion is divided into automatic conversion (implicit conversion) and forced conversion (display conversion), and forced conversion is divided into temporary conversion and permanent conversion.

Conversion modefunction
Temporary conversion(int),(string),(array),(object)...
CastSetType (data, type)
Automatic ConversionOperator type requirements
  1. Temporary conversion: user
    Temporary conversions are in parentheses, which can be converted to integers (int), Booleans (bool), arrays (array), and objects (int).
<?php
$var=123;
var_dump((string)$var); // Implement with string keyword
var_dump($var); // int(123)
$res=strval($var);//Through strval function
var_dump($res); // string(3) "123" 
// Temporary conversion does not change the type of the original data

// http://zhang.com/php/0426/demo.php?id=3&p=5
var_dump($_GET['id']);
// Here you can see that id is a string, and all the content in url defaults to string
// We temporarily convert it to an integer for easy operation
$id = (int)$_GET['id'];
if($id === 3){
    echo "Find Successful!";
}

 $myAge = 18;
 var_dump($myAge,(string)$myAge,(float)$myAge);
 var_dump((array)$myAge,((array)$myAge)[0]);
?>
  1. Permanent conversion: for variables only
<?php
$var=12;
var_dump($var); // int(12) 
settype($var, 'string');
var_dump($var); // string(2) "12"

$s = true;
var_dump($s); // bool(true) 
settype($s,"int");
var_dump($s); // int(1)

$s = 32;
var_dump($s); // int(32) 
settype($s,"array");
var_dump($s); // array(1) { [0]=> int(32) }
// String conversion of arrays makes little sense, and strings themselves can be used as arrays
$str = "admin";
echo $str[0],$str[1]; // ad
// Transform object, default property name scalar
var_dump(((object)$str)->scalar);
?>

Summary of Temporary and Permanent Conversions

<?php
//Temporary conversion
$var = true;
var_dump($var);
$res = (int)$var;
var_dump($res);
var_dump((int)$var, (integer)$var);
echo "<br>";

//Temporarily converted to floating point
var_dump((float)$var, (double)$var, (real)$var);
echo "<br>";

$var = 3.6;
//Discard decimal part
var_dump((int)$var, (integer)$var);
echo "<br>";

//Temporarily convert to string
$var = true;
var_dump((string)$var);
echo "<br>";

//Temporarily convert to Boolean type
$var = "3xuxiaoke";
var_dump((bool)$var, (boolean)$var);
echo "<br>";

//Temporarily convert to empty
$var = "empty";
var_dump((unset)$var);
echo "<br>";

//Temporarily convert to array
$var = 123;
var_dump((array)$var);
echo "<br>";

//Temporary conversion to object
$var = 12.3;
var_dump((object)$var);
echo "<br>";

//Complete temporary conversion through system functions (type + val())
$var = "3xuxiaoke";
$res = intval($var);
var_dump($res);
echo "<br>";

var_dump(floatval($var), doubleval($var));
echo "<br>";

echo "<hr/>";



//Permanent conversion------------------------------------------------------------------------------------------------------------------------------------
$var = 123;

var_dump($var);
echo "<br>";

echo gettype($var);
echo "<br>";

$var = true;

echo gettype($var);
echo "<hr/>";

$var = 123;
var_dump($var);
echo "<br>";

settype($var, "boolean");
var_dump($var);
echo "<br>";

/*type Possible values are:
"boolean" (Or "bool")
"integer" (Or "int")
"float" (Or "double")
"string"
"array"
"object"
"null" */

$var = "3xuxiaoke";
echo settype($var, "int")."</br>";
echo floatval($var)."</br>";
echo gettype($var)."</br>";

// SetType (data, type) setting type GetType (data) getting type
  1. Automatic conversion: system
    Programs automatically convert based on context
    Other types converted to Boolean
  • 0>-false
  • 0.0>-false
  • Empty string "or" or "0" or "0" >-false
  • null>-false
  • Empty array ()>-false
<?php
// '+'requires that the data participating in the calculation be of numeric type, otherwise an automatic conversion will be triggered
echo 123+"456"; // 579
echo 123+(int)"456"; // ====> 579

// String concatenation, expecting both sides to be strings
echo "php". 123 ."cn"; // php123cn
echo "php" . (string)123 . "cn";

// The most commonly used automatic conversion, commonly used for Boolean transformations, either true or false
if(!$email) echo "Mailbox undefined";
// Undefined NULL automatically converts to false

$a = '100abc'; // "100abc"==>100 Non-numeric beginning "abc100"==>0 
$b = 5;
echo "Type is".gettype($a+$b)."Value is".($a+$b);  // integer 105

@$res = null + '10 kg rice';
var_dump($res); // int(10)

$s = 10;
var_dump($s.'kg rice'); // string(9) "10kg rice"
?>

1.4 Data Type Detection

In JavaScript, basic data types can be detected using typeof, and reference data types can be detected using instanceof. In PHP, there are also ways to detect data types, as follows:

  1. Data type of output variable (gettype)
<?php 
 
   $arry = array('a','b','c'); 
 
   echo gettype($arry); //array 
 
 ?> 
  1. The data type, number, and specific content of the output variable (var_dump)
<?php 
 
  $str = 'hello world'; 
 
  var_dump($str);//string(11) "hello world"  
 
?> 
  1. Detects whether a variable is of the specified data type (is_double, is_array, is_int, is_string, and so on), and returns NULL if the result is true and false if it is true.
typefunction
scalaris_int(),is_string(),is_bool()...
Reunite withis_array(),is_object()
specialis_null(),is_resource()

<?php 
 
  $num = 123; 
 
  if(is_array($num)){ 
 
    echo 'This is an array'; 
 
  }else if(is_string($num)){ 
 
    echo 'This is a string'; 
 
  }else if(is_int($num)){ 
 
    echo 'This is an integer'; 
 
  }else if(is_double($num)){ 
 
    echo 'This is a floating point number'; 
 
  } 

  /*function sum1($a,$b){
    if(is_int($a) && is_int($b)){
        return sprintf('%d + %d = %d </br>',$a,$b,($a+$b));
    }else if(is_float($a) && is_float($b)){
        return sprintf('%f + %f = %f </br>',$a,$b,($a+$b));
    }else if(is_numeric($a) && is_numeric($b)){
        return sprintf('%f + %f = %f </br>',$a,$b,($a+$b));
    }else{
        return "Illegal value ";
    }
  }*/
  // php7+: parameter type detection, composite type support, scalar support
  function sum1(float $a,float $b):string{
    return sprintf('%s + %s = %s </br>',$a,$b,($a+$b));
  }
 echo sum1(10,15); // 10 + 15 = 25
 echo sum1("10",15.845); // 10 + 15.845 = 25.845
 echo sum1("ab",6); // illegal value

 /* is_numeric() Detect if it is a numeric string
    is_int() Detect if it is an integer
    is_float() Detect whether it is floating point
    is_string() Detect whether it is a string
    is_bool() Detect whether Boolean
    is_array() Detect if it is an array
    is_object() Detect whether or not it is an object
    is_null() Detect if Null
    is_resource() Detect whether it is a resource
    is_scalar() Detects if it is a scalar type (string, numeric, Boolean)*/

    var_export(is_scalar(12)); // true
    var_export(is_scalar([1,2,3])); // false
    var_export(is_scalar(null)); // false
?> 

1.5 Variable declaration creation

Because PHP is a weakly typed language, variables do not need to be declared in advance before they are used. Variables are automatically created when they are first assigned. This makes the syntax of PHP very different from strongly typed languages such as C and Java.

Declaring a PHP variable must be denoted with a dollar sign'$'followed by the variable name, and then assigned to it with'='. As follows:

<?php
    $a = 1;
    $b = 2;
    $c = 3;
    echo $a.', '.$b.', '.$c; // 1,2,3
?>

1.6 Variable Naming Rules

A valid variable name should meet the following requirements:

  • Variables must start with the $sign, followed by the name of the variable, $is not part of the variable name;
  • The variable name must start with a letter or an underscore;
  • The variable name cannot start with a number;
  • Variable names can only contain letters (Az), numbers (09), and underscores ();
  • Unlike other languages, some keywords in PHP can also be used as variable names (for example t r u e , true, true,for).
  • Identifiers are predefined (reserved words, keywords, class, public) and customized.

Note: Variable names in PHP are case sensitive, and function names are case insensitive, so $var and $Var represent two different variables.

$_str = "PHP Is the best language in the world";        
// The variable name is: _ str, variable value: PHP is the best language in the world

When using multiple words to form variable names, you can use the following naming conventions:

  • Underline nomenclature: Split words that make up variable names with an underscore, for example g e t u s e r n a m e , get_user_name, getu​sern​ame,set_user_name;
  • Hump nomenclature (recommended): the first word is lowercase, followed by the first letter lowercase, for example g e t U s e r N a m e , getUserName, getUserName,getDbInstance;
  • Pascal nomenclature: capitalizes all words that make up a variable name, for example N a m e , Name, Name,MyName,$GetName.

1.8 variable assignment

Is to access the contents of the same variable under different names. When you change the value of one of these variables, the other will also change. Reference assignment uses'&'to denote a reference.

<?php
//php reference variable: different variable names point to the same address

// Pass-by Assignment
//Define a variable a, where memory opens up an area, $a points to that area
$a = 100;
//Define the variable B and assign the value of a variable to b, where two variables ($a and $b) point to the area.
$b = $a;
printf("a=%d,b=%d",$a,$b); // a=10 b=10

//By modifying the value of the $a variable, the php variable has the Copy On Write property, so the area value pointed to by a is copied and overridden, where a and b point to different areas, respectively.
$a = 10;
printf("a=%d,b=%d",$a,$b); // a=10 b=100

// ------------------------

// Reference Assignment-Address Reference
$c = 100;
$d = &$c;
$c = 10;
printf("c=%d,d=%d",$c,$d); // c=10 d=10
//When a reference points, the php variable does not have the Copy On Write attribute and points to the same memory area, and the other variable changes regardless of who changes $c or $d

unset($c); // Just disassociate $c from $d, $d can still be used
var_dump($d); // int(10)

// -------------------------------

// Variable variables use two dollar signs ($)
$a = "hello";
$$a = "world";
var_dump($a); // string(5) "hello"
var_dump($hello); // string(5) "world"
// Both variables are defined: $a has the content "hello" and $hello has the content "world".
// Therefore, it can be expressed as echo'$a ${$a}'; Or echo'$a $hello'; They all output: hello world

1.8 correlation function

  • ob_clean() is a built-in function that empties the contents of the output buffer
  • File_ Put_ The contents() function writes a string to a file
  • The unset() function is used to destroy and release a given variable
  • Both die("string") and exit("string") are abort script execution functions
  • isset() and empty() are used to detect whether a variable is declared and empty
$arr = [1,2,3,4];
var_dump($arr);
$res = print_r($arr,true); // Return the contents of the array directly without printing
file_put_contents("log.txt",$res); // Store array contents in log.txt

ob_clean(); // Built-in function to empty the contents of the output buffer
// The above content will not be output

// Destroy a single variable
unset ($foo);
// Destroy a single array element
unset ($bar['quux']);
// Destroy more than one variable
unset($foo1, $foo2, $foo3);

// Enter information to terminate subsequent program
exit('123'); // Output 123
die('1234'); // Output 1234
$fp = @fopen("./readme.txt","r") or die("Can't open this file!!!");
// In this case, if the fopen function is called and returns a Boolean value of false, die() immediately terminates the script, prints it, and passes it the string "one or two sentences before death".

// isset() determines whether a variable is declared and not NULL
// Returns true if the variable exists and the value is not null or false otherwise
	var_export(isset($username)); // Variable does not define false
	$username = "zhang";
	var_export(isset($username)); // true
// Testing a variable set to NULL with isset() returns FALSE
	unset($username); // null
	var_export(isset($username)); // false
	echo !isset($username)?'Variable not detected':'Variable already defined';

// empty() detects whether a variable is empty (returning true for empty does not return false)
	var_export(empty(18));  // Not empty false
	var_export(empty(""),empty(0),empty(NULL),empty(false));  // Variable is empty bool(true) bool(true) bool(true)
/*
The following variables are considered null when empty is used to determine them:
"" (Empty string)
0 (0 as an integer)
0.0 (0 as floating point number)
"0" (0 as string)
NULL
FALSE
array() (An empty array)
*/

//------------------

1.9 Scope

The scope of a variable (the range in which it can be used) is called the scope of a variable. A variable must be used within its valid range. If it exceeds the valid range, a variable loses its meaning. PHP variables can be divided into global and local variables by scope.

Variables that can be used anywhere in the current source code (outside the function) are called global variables and have a global scope. Variables that can only be used inside functions that define them are called local variables and have local scopes.

Local Variables and Local Scopes

A local variable is a variable defined within a function and can only be used within the function that defines it. Local variables are automatically destroyed at the end of a function call.

<?php
    function example(){
        $a = "php Chinese net";  // Defining variable a within a function
        echo "local variable a The value is:".$a."<br>";
    }
    example();
    if(isset($a)){    // Call $a outside the function and print the following if $a exists
        echo "Calling local variables within a function outside a function a,The values are:".$a;
    }
// Only the value of local variable a in the function body is printed: php Chinese net.
?>

Global variables and global scope

A global variable is a variable defined outside of all functions whose domain is anywhere in the current source code but is not available inside the function. Global variables persist during program execution and are only destroyed when the program is finished running.

<?php
    $a = "php Chinese net";      // Defining a global variable outside a function
    function example(){
        if(isset($a)){
            echo "Calling global variables within a function a,The values are:".$a;
        }
    }
    example();
    echo "Calling global variables outside a function a,The values are:".$a;
// "Call global variable a outside the function with value: php Chinese net" is printed only outside the function.
// You can see from the results that $a was not successfully called inside the function, but outside the function.

// --------------- Use external global variables inside functions
// 1. Calling global variables within a function body requires a global keyword reference
    function example(){
        global $a; // Referencing external global variables within a function body by globalkeywords
        if(isset($a)){
            echo "Calling global variables within a function a,The values are:".$a;
        }
    }
// 2. Use a superglobal variable $GLOBALS['variable']
	function example(){
        if(isset($GLOBALS['a'])){
            echo "Calling global variables within a function a,The values are:".$GLOBALS['a'];
        }
    }
?>

Predefined and static variables

Predefined variables (superglobal variables)

Predefined variables, also known as superglobal variables, can be used in all scopes without having to be declared in advance. These predefined variables provide information about user sessions, the environment of the user's operating system, and the environment of the local operating system.

Common predefined variables are as follows:

  • $GLOBALS: All available variables in the global scope;
  • $_ SERVER: Information about the server and execution environment;
  • $_ REQUEST: Contains G E T , _GET, G. ET, _ POST and $_ All information about COOKIE;
  • $_ POST: Data submitted through the POST method;
  • $_ GET: Data submitted by the GET method;
  • $_ FILES: File data uploaded to the server via POST;
  • $_ ENV: An array of variables passed environmentally to the current script;
  • $_ COOKIE: An array of variables passed to the current script through HTTP Cookies;
  • $_ SESSION: The current script can be an array of SESSION variables.

$GLOBALS is an array containing all variables in the global scope whose name is the key to the array.

<?php
    $name = 'php Chinese net';
    $title = 'PHP Predefined variables';
    function demo(){
        static $str = 'PHP Course';
        $url = 'http://www.php.cn';
    }
    echo "<pre>";
    var_dump($GLOBALS);
	echo "</pre>";
/*
array(7) {
  ["_GET"]=>
  array(0) {
  }
  ["_POST"]=>
  array(0) {
  }
  ["_COOKIE"]=>
  array(0) {
  }
  ["_FILES"]=>
  array(0) {
  }
  ["GLOBALS"]=>
  array(7) {
    ["_GET"]=>
    array(0) {
    }
    ["_POST"]=>
    array(0) {
    }
    ["_COOKIE"]=>
    array(0) {
    }
    ["_FILES"]=>
    array(0) {
    }
    ["GLOBALS"]=>
    *RECURSION*
    ["name"]=>
    string(12) "php Chinese Web"
    ["title"]=>
    string(19) "PHP Predefined variable
  }
  ["name"]=>
  string(12) "php Chinese Web"
  ["title"]=>
  string(19) "PHP Predefined variable
}  // Note: $GLOBALS does not contain local and static variables in the function.
*/
?>
static variable

Static variable is a special local variable. From the previous learning, we know that if you define a local variable inside a function, it will be destroyed after the function call ends and cannot be used anymore. Static variables, unlike static variables, persist after they are initialized for the duration of the program.

Compared with local variables, static variables have the following characteristics:

  • When the function is executed, the static variable does not disappear.
  • Static variables can only be used inside functions;
  • Static variables are only initialized once;
  • Initialization of static variables can be omitted and the default value is null.
  • The initial value of a static variable can only be a specific string, numeric value, and so on, not an expression.

The static keyword is used to define static variables as follows:

static variable = value;

Define a static variable to record the number of function calls, and define a local variable to compare with a static variable in the following code:

<?php
    // A static variable does not mean that its value cannot be changed; that which cannot be changed is called a constant. In fact, the value of a static variable can be changed, and it will keep the latest value. Static is called because it does not change with the call and exit of a function. That is, the last time we called a function, if we assigned a value to a static variable, that value would remain the same the next time we called the function.
    function demo(){
        static $a = 0;
        $b = 0;
        $a++;
        $b++;
        echo 'No. '.$a.' Secondary run demo function, local variable $b The value is:'.$b.'<br>';
    }
    demo();
    demo();
    demo();
    demo();
/*
The demo function is run for the first time, and the value of the local variable $b is:1
 The second time the demo function runs, the value of the local variable $b is:1
 Run the demo function for the third time, and the value of the local variable $b is:1
 Run demo function for the fourth time, the value of local variable $b is:1
*/
?>

2. Detailed explanation of PHP constants

Constants are those that cannot be changed. Once defined in PHP, constants cannot be modified or undefined.

PHP constants are usually used to store data that is unchanged and does not want to change. They can only be of four scalar data types: integer, floating point, string, Boolean, but they support array types beginning with PHP7.

Compared with variables, constants have the following characteristics:

  • Constants are preceded by no dollar sign ($);
  • Constants can only be defined with define() and const;
  • Constants, classes, interfaces, and functions are global in scope.
  • Once a constant is defined, it cannot be redefined or undefined.
  • Constant names recommend all uppercase letters

Declarations and use of 2.1 constants

  • define(): function
define("NATION","China");
define("AGE",18);
  • const:keyword
const NAME = 'zhangshuai';
const GENDER = "man";
$user = sprintf('Full name:%s,Gender:%s,Age:%d,Nationality:%s',NAME,GENDER,AGE,NATION);
echo $user;
// Name: Zhangngshuai, gender: man, age: 18, nationality: China


// Constants defined in classes can only be defined using the const keyword
class User{
    // Constant must initialize assignment
    const APP_PATH = '0426/demo.php';
}

2.2 Predefined and Magic Constants

Predefined Constants

Definition constants, as the name implies, are pre-defined constants in PHP. Using these pre-defined constants can help us get some information in PHP, such as the operating system of the current computer, the version of PHP currently in use, and so on. Also note that predefined constants are case sensitive.

View system predefined constants: echo'<pre>'. Print_ R(get_defined_constants(true), true). "</pre>";

Some predefined constants in PHP are listed below:

  • PHP_VERSION: The version number of the current PHP;
  • PHP_OS: The name of the current operating system;
  • PHP_EOL: System line break, Windows is (\r\n), Linux is (\n), MAC is (\r);
  • PHP_INT_MAX: The largest integer currently supported by PHP;
  • PHP_INT_MIN: The smallest integer supported by current PHP;
  • PHP_ EXTENSION_ Extended directory for DIR:PHP;
  • TRUE: true for Boolean type;
  • FALSE: false of Boolean type;
  • NULL: Null value.
// Set only error_in the current script Report() Domain error reporting level for the area following the function call
error_reporting(E_ALL);
// A parameter can be an integer or a corresponding constant identifier, and the form of a constant is recommended.

    // Use error_reporting(0) or prefixing a function with @ suppresses error output to prevent error messages from disclosing sensitive information.

magic constant

Magic constants are special predefined constants that can vary depending on where they are used. Magic constants are usually underlined by two u Start with two underscores_u Ending.

There are eight magic constants in PHP, as follows:

  • _u LINE_u: The current line number in the file;
  • _u FILE_u: The absolute path of the current file (including the file name);
  • _u DIR_u: The absolute path of the current file (excluding the file name) is equivalent to dirname (u FILE_u);
  • _u FUNCTION_u: The name of the current function (or method);
  • _u CLASS_u: The current class name (including the scope or namespace of the class);
  • _u TRAIT_u: Current trait name (including the scope or namespace of the trait);
  • _u METHOD_u: Current method name (including class name);
  • _u NAMESPACE_u: Namespace name of the current file.

Note: Unlike predefined constants, magic constants are case insensitive.

<?php
    echo "<br/>Root path of current file:".__dir__;
 	echo "<br/>Path to current file:".__FILE__;
    echo "<br/>Current number of rows:".__LINE__;
    echo "<br/>current PHP Version information for:".PHP_VERSION;
    echo "<br/>Current operating system:".PHP_OS;
/*
Root path of current file: E:\zhang0426
 Path to current file: E:\zhang0426demo. PHP
 Current number of rows: 4
 Current PHP version information: 7.2.31
 Current Operating System: WINNT
*/
function getName(){
    echo "<br>Current function name:".__FUNCTION__;
}
getName(); // Current function name: getName

class Person{
    public function walk(){
    	echo "The current class name is ".__CLASS__;
        echo "Current class and method names ".__METHOD__;
    }
}
$zhang = new Person;
$zhang->walk(); // Current class name is Person Current class name and method name is Person::walk
?>

Topics: PHP