This is the 21st day of my participation in Gwen Challenge
For more information about PHP and syntax, see php.net’s documentation :PHP Manual or PHP Tutorial
PHP knowledge
PHP (PHP: Hypertext Preprocessor) is a common open source scripting language.
PHP file
- PHP files can contain text, HTML, JavaScript code, and PHP code
- The PHP code executes on the server and the result is returned to the browser in pure HTML
- The default file extension for PHP files is “.php”
PHP knowledge
- Start tag
<? php
And closing tag? >
. The content between the opening and closing tags is parsed and executed as PHP code. - Get the get request parameters
$_GET
<body>
<div id="head"></div>
<div id="content">
$id=$_GET['id'];// Get the get query string argument
if($id= ='1') {// Read the contents of 1. TXT and print echo
$str = file_get_contents('./1.txt');
echo $str;
}
? >
</div>
<div id="footer"></div>
</body>
Copy the code
echo
output
Echo – can print one or more strings print – can print only one string and always return 1
echo "I want to learn PHP!
";
echo "This is one."."String,"."Used"."More than"."Parameters.";
print "I want to learn PHP!";
? >
Copy the code
- use
//
and/ * * /
annotate - Variable to
$
At the beginning, there is no command to declare a variable, the variable is created at the first assignment, can be used directly, alphanumeric underscore (cannot be the first digit), the first definition of the variable should be given a value. - Constants cannot be changed. Define constants
Define (' PI ', 3.1415926)
A constant consists of letters, underscores (_), and numbers. The number cannot start with a letter$
Modifier).Constants are available throughout the script. Constants can only be Boolean, INTEGER, float, string. Define (' PI ', 3.1415926)
Is a function that returns true if a constant is defined and false if it is not.var_dump()
Used to output information about variables.print_r()
Used to print variables and present them in a form that is easier to understand.- PHP data types:
Scalar types — String (String), Integer (Integer, PHP_INT_MAX and PHP_INT_MIN), Float (Float is a number with a decimal part, or an exponent), Boolean (Boolean);
Scalar values cannot be split into smaller units.
Compound types — Array, Object, callable;
Special type — resource, NULL (NULL, case insensitive).
- An array of. use
array()
or[]
(>=php5.4) Define an array
The count() function returns the length of the array
- Indexed array: An array with a numeric index.
- Associative array: An array with a specified key. An array that uses the specified key assigned to the array (the key is either string or int)
- Multidimensional array – An array containing one or more arrays
// Create an indexed array
$cars=array("Volvo"."BMW"."Toyota");
// $cars=["Volvo","BMW","Toyota"];
// $cars[0]="Volvo";
// $cars[1]="BMW";
// $cars[2]="Toyota";
var_dump($cars);
echo count($cars); // count() the length of the array
// Iterate over the indexed array
$arrlength=count($cars);
for($i=0;$i<$arrlength;$i{+ +)echo $cars[$i];
echo "<br>";
}
echo "<br>";
$arrlength=count($cars);
// Array element types are inconsistent
$stu0 = array('Joe'.13);
An associative array is an array that uses the specified key (string or int) assigned to it.
// There are two ways to create associative arrays
$stu1 = array(
'name'= >'Joe'.'age'= >13
);
$stu2['name'] ='bill';
$stu2['age'] =14;
/ / traverse
foreach($stu2 as $key= >$value)
{
echo $key . " 是:" . $value;
echo "<br>";
}
? >
Copy the code
- Which values are equal to FALSE
-
- The Boolean value FALSE itself
-
- The integer 0
-
- Floating point 0.0
-
- Empty string and string “0”
-
- An array that does not contain any elements
-
- Special type NULL(including variables that have not yet been assigned)
-
- Generate SimpleXML objects from empty tags
All other values are considered TRUE(including any resource and NAN)
(bool) Type conversion
$int_a=0;
var_dump( (bool)$int_a ); // false
? >
Copy the code
- Expression: Anything that has a value.
Expressions are one of the most important cornerstones of PHP; almost anything you write is an expression.
The most basic expressions are constants and variables. If $a = 5, the value of “5” is 5, and “5” is an expression with the value of “5”; $b = $a, $a is an expression that also has a value of 5.
Functions are also expressions.
PHP is an expression oriented language
- The operator
- Arithmetic operator
- The assignment operator
- Increment decrement operator
- Comparison operator
- Logical operator
- String operator
- Process control
-
Sequential standard execution is sequential execution
-
conditions
1) – if statements
A direct use of if(… elseif… Else) statement condition judgment and execution.
Another way to use
and
implement conditional statements (
,
,
and
)
if(true) {echo ' This is a heading
';
echo ' This is a heading
';
}
else if(true){
}
elseif(true){
}
else{}? >
if(true) :? >
<h1 class="head"> < span style = "max-width: 100%h1>
<?php endif; ? >Copy the code
2) – a switch statement
Use the Switch statement to avoid lengthy if.. elseif.. Else code block.
switch (expression)
{
case label1:
// expression = code executed at label1;
break;
case label2:
// expression = code executed when label2;
break;
default:
// The code executed when the value of the expression satisfies all of the above cases;
}
Copy the code
- cycle
1) – while loop
while(true){
}
Copy the code
Alternative syntax
while() :? >
// code
endwhile; ? >
Copy the code
2) – the foreach loop
foreach( $as as $a ){
}
Copy the code
and
foreach( $as as $a_key= >$a_value ){
}
Copy the code
Alternative syntax
foreach(expr): ? >
/ / the loop body
endforeach; ? >`
Copy the code
3) – a for loop
You can specify the number of cycles.
for (init counter; test counter; increment counter) {
code to be executed;
}
for ($x=0; $x< =10; $x{+ +)echo "The numbers are:$x <br>";
}
Copy the code
- function
function functionName($a.$b){}// Default value parameter
function functionName($a.$b=4){
/ / the return value
// return $value
}
? >
Copy the code
- PHP variable scope: The scope of a variable is the part of the script where the variable can be referenced/used (scope).
PHP has four different variable scopes: local, global, static, and parameter
- Local and global scopes
Variables defined outside all functions have global scope. Global variables can be accessed by any part of the script except functions. To access a global variable within a function, use the global keyword.
PHP stores all global variables in an array named $GLOBALS[name], which is internally accessible through $GLOBALS
$x=5;
$y=10;
function myTest()
{
global $x.$y;
$y=$x+$y;
}
myTest();
echo $y; / / output 15
? >
Copy the code
Corresponds to the $GLOBALS mode
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y'] =$GLOBALS['x'] +$GLOBALS['y'];
}
myTest();
echo $y;
? >
Copy the code
- The Static scope
When a function completes, all its variables are usually removed. However, if you want a local variable not to be deleted. You can use the static keyword when declaring a variable for the first time:
function myTest()
{
static $x=0;
echo $x;
$x+ +;echo PHP_EOL; / / a newline character
}
myTest(); / / 0
myTest(); / / 1
myTest(); / / 2
? >
Copy the code
- Parameter Parameter scope (parameter)
Parameter declarations are part of function declarations.
function myTest($x)
{
echo $x;
}
myTest('Galois');
myTest(8888);
Copy the code
- Classes and objects
Property declarations begin with the keyword public, protected, or private and are followed by a normal variable declaration.
Use of the var keyword
Class attributes must have qualifiers. In PHP, class attributes must be defined as either public, protected, or private. So if you don’t have those three modifiers, you have to use var. Var is treated as public since PHP5. Var is an alias for public.
/ / inheritance
class ClassName extends ParentClass{
/* Member variable */
var $url;
var $title;
// constructor
function __construct( $par1.$par2 ) {
$this->url = $par1;
$this->title = $par2;
}
// destructor
function __destruct() {
print "Destroyed" . $this->name . "\n";
}
function printIP()
{
echo $this->url;
echo $this->title; }}// Create an object
$obj=new ClassName();
? >
Copy the code
- File splitting
Modular programming. Use the require or include keyword to import other PHP files, and then use PHP code, functions, variables, and so on from that file
Require_once and include_once can introduce the same file multiple times without reporting an error. Both are introduced only once, and will not be introduced repeatedly.
Amy polumbo HP / / file
function add($a.$b){
return $a+$b;
}
? >
P. HP / / file
require './a.php'; // The error level is higher than include
// include './a.php'; // The code can still be executed after the error is introduced
// require_once('./a.php'); // require_once "./a.php";
// include_once "./a.php"; // include_once('./a.php');
$c=add(3.4);
echo $c;
? >
Copy the code
- Commonly used functions
printf()
Prints a formatted stringsprintf()
Returns a formatted stringprint()
Outputs (a) string with only one argument.
$name="Zhang";
$age=16;
// Format string output
printf('I'm % S and I'm % D.'.$name.$age); // Returns the length of the resulting string
// Returns a formatted string
$str=sprintf('I'm % S and I'm % D.'.$name.$age);
echo $str;
print('Print out');
// Exit the current execution
exit(a);? >
Copy the code
print_r()
Print variables in a nice format
Bool print_r (mixed $expression [, bool $return]) parameter Description
$expression: The variable to print. If a string, INTEGER, or float variable is given, the value itself will be printed. If an array is given, the keys and elements will be displayed in a certain format. Object is similar to an array.
$return: Optional, if true, the result is not printed but assigned to a variable, false, the result is printed directly.
- PHP single quotes and double signals
The contents of single quotes are not interpreted (\n is not printed as a newline, variables are not parsed as variable values, etc.), i.e. the contents are the same as the input
The contents of the double quotes will be interpreted, that is, variables in the content will be parsed.
-
- Insert single quotation marks between double quotation marks. If there are variables in single quotation marks, the variables will be interpreted
-
- Because double quotes are interpreted, they are less efficient than single quotes, so use single quotes in YOUR PHP code. Double quotation marks are used when parsing contained variables
<pre></pre>
Tag, used to leave content such as line feeds as is