PHP notes super detailed! ! !

Preliminary PHP syntax

PHP concept : PHP (full name: PHP: Hypertext Preprocessor, ie "PHP: Hypertext Preprocessor") is an open source scripting language that runs on the server side and can be embedded into HTML.

PHP file : can contain text, HTML, JavaScript code, and PHP code. PHP code is executed on the server, and the result is returned to the browser in plain HTML. The default file extension is ".php".

Function of PHP :

  • Generate dynamic page content
  • Create, open, read, write, close files on the server
  • Collect form data
  •  Send and receive cookies
  • Add, delete, modify data in your database
  • Restrict users from accessing some pages on your site
  • encrypted data

Advantages of PHP :

  • PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers in use today (Apache, IIS, etc.)
  • PHP provides extensive database support
  • PHP is free and can be downloaded from the official PHP resource

PHP scripts can be placed anywhere in the document. PHP scripts start with <?php and end with ?>.

PHP statement separator

Every line of code in PHP must end with a semicolon . A semicolon is a separator used to separate instruction sets.

//定义内容
<?php
$a=5;
echo "Hello World";
?>

Special Instructions:

  1. The tag terminator ?> in PHP has the effect of its own statement terminator, and the last line of PHP code can have no statement separator.
  2. A lot of code writing in PHP is not embedded in HTML, but exists alone.

PHP comments

PHP comment
Classification line comment block comment
symbol

                    //

                    #

                            /*

                           */

explain //: Everything that follows is a comment /**/: All are comments until */ appears in the middle

PHP output

There are two basic output methods in PHP: echo and print.

The difference between the two:

The difference between echo and print
/ echo print
output characters Can output one or more strings Only one string is allowed
output speed faster slower
return value no return value The return value is 1

echo 

output string:

<?php
echo "Hello World";
echo "1","2","3";
?>

output variable:

<?php
$a=TFboys;
$team=array("Karry Wang","Roy Wang","Jackson Yee");

echo "$a";
echo "$a是一个实力派的唱跳组合";
echo "TFboys的队长是{$team[0]}";
?>

print

output characters

<?php
print "TFboys是我最喜欢的一个组合";
?>

output variable

<?php
$a=TFboys;
$team=array("Karry","Roy","Jackson Yee");

print "$a";
print "$a是一个实力派的唱跳组合";
print "TFboys的队长是{$team[0]}";
?>

PHP variables

Variable concept: A variable is a container for storing data.

Variable naming rules:

  1. Variable names in PHP must start with the "$" symbol;
  2. The name is composed of letters, numbers and underscore "_", but cannot start with a number;
  3. Allow Chinese variables in PHP (not recommended);
  4. Variable names are case sensitive;
  5. Variable names cannot contain spaces.

variable scope

PHP has four different variable scopes: local, global, static, parameter.

Variable scope difference
serial number scope describe
1

local

local scope

2

global

global scope

3

static

static scope

4

parameter

Function parameter scope

 

PHP global keyword

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

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

PHP stores all global variables in an array called $GLOBALS[ index ]. index  is the name of the variable. This array can be accessed inside the function, and can also be used directly to update global variables, so the above code can also be written like this:

 static scope

When a function completes, all its variables are deleted. If you want a local variable not to be deleted, you need to use static. 

use of variables

1. Definition: Add the corresponding variable name in the system (in memory)

2. Assignment: Data can be assigned to the variable name (can be done at the same time as the definition)

3. The stored data can be accessed by variable name

4. Variables can be deleted from memory

//定义变量:在PHP中不需要任何关键字定义变量(赋值)
$var1;          //定义变量
$var2 = 1;      //定义并赋值

//访问变量
echo $var2;     //通过$var2变量名字找到存储的内容1,然后输出。

//修改变量
$var 2 = 2;
echo '<hr/>',$var2;

//删除变量:使用unset(变量名字)
unset($var2);
echo $var2;

predefined variable

Predefined variables: variables defined in advance, storing many data that need to be used (predefined variables are all arrays)

$_GET  : Get the data submitted by all forms in get mode

$_POST  : The data submitted by POST will be saved here

$_REQUEST  : Both GET and POST submissions will be saved

$GLOBALS : all global variables in PHP

$_SERVER : server information

$_SESSION  : session session data

$_COOKIE  : cookie session data

$_ENY : environment information

$_FILES : User uploaded file information

mutable variable

Variable variable: If the value stored in a variable happens to be the name of another variable, then you can directly access a variable to get another variable; add an additional $ sign before the variable.

PHP constants

Constant : const/constant is an unchangeable quantity (data) that cannot be changed while the program is running. Once a constant is defined, usually the data cannot be changed (user level).

constant definition form

1. Use the define() function:

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
其中:
name:必选参数,常量名称,即标志符。
value:必选参数,常量的值。
case_insensitive :可选参数,如果设置为 TRUE,该常量则大小写不敏感。默认是大小写敏感的。

Naming rules for constant names

  1. Constants do not need to use the "$" symbol, once used the system will be considered as a variable
  2. Constant names are composed of letters, numbers and underscores, and cannot start with a number
  3. Constant names are usually capitalized (to distinguish them from variables)
  4. Constant naming rules are looser than variables, and some special characters can be used. This method can only be defined by define

Attention to detail:

  1. The constants defined by define and const are different: the difference in access rights
  2. The definition of constants is usually not case-sensitive, but it can be distinguished, you can refer to the third parameter of the define function

Example:

1. Case sensitive:

<?php
//区分大小写的常量名
define("TFBOYS","Good!!!");
echo TFBOYS;
echo'<br>';
echo tfboys
?>

2. Case insensitive:

<?php
//区分大小写的常量名
define("TFBOYS","Good!!!",ture);
echo TFBOYS;
echo'<br>';
echo tfboys
?>

 constants are global

After the constant is defined, it is global by default and can be used anywhere in the entire running script.

system constant

System constants: The constants defined by the system help users can be directly used by users.

Several commonly used system constants:

PHP_VERSION: PHP version number

PHP_INT-SIZE: integer size

PHP_INT-MAX: The maximum value that can be represented by integers (in PHP, integers are allowed to have negative numbers: signed)

There are also some special constants in PHP, they start with a double underscore + constant name + end with a double underscore, this kind of constant is called a system magic constant: the value of a magic constant usually changes with the environment, but the user cannot change it

--DIR--: The absolute path of the computer where the currently executed script is located

--FILE--: The absolute path of the computer where the currently executed script is located

--LINE--: the current line number

--CLASS--: The current class

<?php
//文本中的当前行号
echo '这是第"'.__LINE__.'"行.<br>';

//文件的完整路径和文件名
echo '该文件位于 "'.__FILE__.'" <br>';

//文件所在的目录
echo '该文件位于"'.__DIR__.'"<br>';

//返回函数的名字
function TFboys(){
	echo '函数名为:'.__FUNCTION__;
}
TFboys();
?>

PHP data types 

Data type : data type, in PHP, refers to the type of the stored data itself, not the type of the variable. PHP is a weakly typed language, variables themselves have no data types.

PHP supports eight data types:

  • String (string)
  • Integer
  • Float (floating point type)
  • Boolean
  • Array (array)
  • Object
  • NULL (empty value)
  • Resource (resource type)

PHP string

A string is a sequence of strings, like "Hello World", usually used when outputting text, wrapping the text in double quotes or single quotes.

<?php 
$x = "TFBOYS";
echo $x;
echo "<br>"; 
$x = 'very good!!!';
echo $x;
?>

PHP integer

Four integer definitions are provided in PHP: decimal definition, binary definition, octal definition, hexadecimal definition

Decimal system: enter 1 every 10, and the numbers that can appear are 0-9;

Binary: Every 2 enters 1, and the numbers that can appear are 0-1;

Octal system: every 8 enters 1, and the numbers that can appear are 0-7;

Hexadecimal: every 16 enters 1, the numbers that can appear are 0-9 and af, a means 10, and so on.

 PHP float

Floating-point type: Decimal type and integers that exceed the storage range of integers (the accuracy is not guaranteed), and the accuracy range is about 15 significant figures.

There are two ways to define a floating point type:

$f=1.23;

$f=1.23e10; //Scientific notation, where e means 10

PHP Boolean type

Boolean type: two values ​​true and false, usually used for judgment comparison

PHP array

Arrays can store multiple values ​​in one variable.

Example:

<?php
$a=TFboys;
$team=array("Karry","Roy","Jackson Yee");
?>

PHP object

Object data types can be used for data storage.

In PHP, objects must be declared.

First, a class object is declared using the class keyword. A class is a structure that can contain properties and methods.

Then define the data type in the class and use the data type in the instantiated class.

 PHP NULL value

A NULL value indicates that the variable has no value, and NULL is a value whose data type is NULL.

Variable data can be cleared by setting the variable value to NULL:

<?php
$x="Hello world!";
$x=null;
var_dump($x);      //返回为NULL
?>

PHP operator

PHP Arithmetic Operators

PHP operator
operator name describe example result
x + y add sum of x and y 2 + 2 4
x - y reduce difference between x and y 5 - 2 3
x * y take product of x and y 5 * 2 10
x / y remove quotient of x and y 15 / 5 3
x % y modulo (remainder of division) Remainder of dividing x by y 5 % 2
10 % 8
10 % 2
1
2
0
- x reconciliation negate x
<?php
$x =2;
echo -$x;
?>
-2
a . b Apposition concatenates two strings "Hi" . "Ha" Haha

intdiv(a,b) (PHP7+ version)

round down Divide the first parameter by the value of the second parameter and round (round down) var_dump(intdiv(10, 3)) int(3)

 PHP assignment operator

PHP assignment operator
operator Equivalent to describe
x = y x = y The left operand is set to the value of the expression on the right
x += y x = x + y add
x -= y x = x - y reduce
x *= y x = x * y take
x /= y x = x / y remove
x %= y x = x % y modulo (remainder of division)
a .= b a = a . b concatenates two strings

PHP increment/decrement operators

PHP increment/decrement operators
operator name describe
++ x pre-increment Increment x by 1, then return x
x ++ post-increment return x, then add 1 to x
-- x pre-decrement Subtract 1 from x and return x
x -- 后递减 返回 x,然后 x 减 1

PHP 比较运算符

PHP 比较运算符
运算符 名称 描述 实例
x == y 等于 如果 x 等于 y,则返回 true 5==8 返回 false
x === y 绝对等于 如果 x 等于 y,且它们类型相同,则返回 true 5==="5" 返回 false
x != y 不等于 如果 x 不等于 y,则返回 true 5!=8 返回 true
x <> y 不等于 如果 x 不等于 y,则返回 true 5<>8 返回 true
x !== y 绝对不等于 如果 x 不等于 y,或它们类型不相同,则返回 true 5!=="5" 返回 true
x > y 大于 如果 x 大于 y,则返回 true 5>8 返回 false
x < y 小于 如果 x 小于 y,则返回 true 5<8 返回 true
x >= y 大于等于 如果 x 大于或者等于 y,则返回 true 5>=8 返回 false
x <= y 小于等于 如果 x 小于或者等于 y,则返回 true 5<=8 返回 true

PHP逻辑运算符

PHP逻辑运算符
运算符 名称 描述 实例
x and y 如果 x 和 y 都为 true,则返回 true x=6
y=3
(x < 10 and y > 1) 返回 true
x or y 如果 x 和 y 至少有一个为 true,则返回 true x=6
y=3
(x==6 or y==5) 返回 true
x xor y 异或 如果 x 和 y 有且仅有一个为 true,则返回 true x=6
y=3
(x==6 xor y==3) 返回 false
x && y 如果 x 和 y 都为 true,则返回 true x=6
y=3
(x < 10 && y > 1) 返回 true
x || y 如果 x 和 y 至少有一个为 true,则返回 true x=6
y=3
(x==5 || y==5) 返回 false
! x 如果 x 不为 true,则返回 true x=6
y=3
!(x==y) 返回 true

PHP数组运算符

 PHP数组运算符
运算符 名称 描述
x + y 集合 x 和 y 的集合
x == y 相等 如果 x 和 y 具有相同的键/值对,则返回 true
x === y 恒等 如果 x 和 y 具有相同的键/值对,且顺序相同类型相同,则返回 true
x != y 不相等 如果 x 不等于 y,则返回 true
x <> y 不相等 如果 x 不等于 y,则返回 true
x !== y 不恒等 如果 x 不等于 y,则返回 true

三元运算符

语法格式为: (expr1) ? (expr2) : (expr3)

对 expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3。

组合比较符(PHP7+)

语法:$c = $a <=> $b;

  • 如果 $a > $b, 则 $c 的值为 1
  • 如果 $a == $b, 则 $c 的值为 0
  • 如果 $a < $b, 则 $c 的值为 -1

错误抑制符

在PHP中有一些错误可以提前预知,但是这些错误可能无法避免,但是又希望不报错给用户看,可以使用错误抑制符处理。

@:在可能出错的表达式前面使用@符号即可。

//错误抑制符
$a = 10;
$b = 0;

@($a % $b);   //正常情况下会报错,因为被除数不能为0,可以使用@错误抑制符

连接运算符

连接运算:是PHP中将多个字符串拼接的一种符号

. :将两个字符串连接到一起

.= :复合运算,将左边的内容与右边的内容连接起来,然后重新赋值给左边变量。

//连接运算符

$a = 'karry';
$b = 'wang';

echo $a . $b;     //将变量a和b连接起来 ==> 结果是karry wang

$a .= $b;    //可以理解成 $a = $a . $b;将a重新赋值
echo $a;  //结果是karry wang

流程控制

控制分类

顺序结构:代码从上往下,顺序执行。(代码执行的最基本结构)

分支结构:给定一个条件,同时有多种可执行代码,根据条件执行某一代码 (if分支和switch分支)

循环结构:在某个控制范围内,指定的代码可以重复执行

 PHP if 分支循环

If:如果的意思,给定一个条件,同时为该条件设置多种(两种)情况,然后通过条件判断来实现具体的执行段。

if语句

if (条件)
{
    条件成立时执行的代码;
}

if...else语句

//if...else语句

if (条件)
{
    条件成立时执行的代码;
}
else
{
    条件不成立时执行的代码;
}

if...elseif...else语句

//if...elseif...else语句
if (条件)
{
    if条件成立时执行的代码;
}
elseif (条件)
{
    elseif 条件成立时执行的代码;
}
else
{
    条件不成立时执行的代码;
}

PHP switch 循环

switch:可以根据多个不同条件执行不同动作

(PHP中switch语句不遇到break不会自己转弯,所以break不可以漏掉)

while循环语句

//while 循环语句

while (条件)
{
    要执行的代码;
}

do...while循环语句

do..while语句会至少执行一次代码,然后检查条件,只要条件成立,就会重复进行循环。

do
{
    要执行的代码;
}
while (条件);

PHP for 循环

循环执行代码块指定的次数,或者当指定的条件为真时循环执行代码块。

for循环

for:用于预先知道脚本需要运行的次数的情况

for (初始值;条件;增量)
{
    要执行的代码;
}

参数:
初始值:初始化一个变量值,用于设置一个计数器
条件:循环执行的限制条件,ture:继续循环,false:循环结束
增量:用于递增计数器

 foreach循环

用于遍历数组

foreach ($arry as $value)
{
    要执行的代码;
}

 函数

创建PHP函数

<?php
function functionName()
{
    要执行的代码
}
?>

PHP函数准则:函数名称以字母或者下划线开头,不能以数字开头

 添加函数

为了给函数增加更多的功能,可以添加函数,类似于变量,在括号内指定

实例1(一个参数)

<?php
function name($fname)  //定义一个参数
{
	echo $fname."Wang.<br>";
}
echo "my husband is ";
name("Karry ");     //调用参数
echo "my husband's friend is ";
name("Roy ");
echo "my sister's husband is ";
name ("Yibo ");
?>

输出不同的名字,但是姓是相同的:

 实例2(两个参数)

<?php
function name($fname,$str)   //定义两个参数
{
	echo $fname."Wang".$str."<br>";   //使用.连接两个参数
}
echo "my husband is ";
name("Karry ","♥");    //调用参数
echo "my husband's friend is ";
name("Roy ","!");
echo "my sister's husband is ";
name ("Yibo ","*");
?>

 返回值

如果让函数返回一个值,需要使用return语句

实例

<?php
function team($leader,$member)
{
	$TFboys=$leader."、".$member;
	return $TFboys;
}

echo "TFboys = ".team("Karry Wang","Roy Wang、Jackson Yee");
?>

PHP面向对象

对象有三个特征:

对象的行为:对对象的操作

对象的形态:施加方法后对象如何相应

对象的表示:相当于身份证,具体区分在相同的行为与状态下有什么不同

 比如animal就是一个抽象类,猫、狗就是具体的对象,有颜色属性,可以跑等行为状态 

面向对象内容:

  •  − 定义了一件事物的抽象特点。类的定义包含了数据的形式以及对数据的操作。

  • 对象 − 是类的实例。

  • 成员变量 − 定义在类内部的变量。该变量的值对外是不可见的,但是可以通过成员函数访问,在类被实例化为对象后,该变量即可成为对象的属性。

  • 成员函数 − 定义在类的内部,可用于访问对象的数据。

  • 继承 − 继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。在定义和实现一个类的时候,可以在一个已经存在的类的基础之上来进行,把这个已经存在的类所定义的内容作为自己的内容,并加入若干新的内容。

  • 父类 − 一个类被其他类继承,可将该类称为父类,或基类,或超类。

  • 子类 − 一个类继承其他类称为子类,也可称为派生类。

  • 多态 − 多态性是指相同的函数或方法可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。

  • 重载 − 简单说,就是函数或者方法有同样的名称,但是参数列表不相同的情形,这样的同名不同参数的函数或者方法之间,互相称之为重载函数或者方法。

  • 抽象性 − 抽象性是指将具有一致的数据结构(属性)和行为(操作)的对象抽象成类。一个类就是这样一种抽象,它反映了与应用有关的重要性质,而忽略其他一些无关内容。任何类的划分都是主观的,但必须与具体的应用有关。

  • 封装 − 封装是指将现实世界中存在的某个客体的属性与行为绑定在一起,并放置在一个逻辑单元内。

  • 构造函数 − 主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。

  • 析构函数 − 析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。析构函数往往用来做"清理善后" 的工作(例如在建立对象时用new开辟了一片内存空间,应在退出前在析构函数中用delete释放)。

通过 TFboys类 创建了三个对象:Karry、Roy、Jackson。 

$TFboys = new Karry ();
$TFboys = new Roy ();
$TFboys = new Jackson();

 PHP类定义

<?php
class tfboys {
    var $var1;
    var $var2 = "constanr string";

    function myunc ($arg1,$grg2){
    }
}
?>

类使用class关键字后加类名定义

类名后的一对大括号{}内可以定义变量和方法

类的变量使用var来声明,变量也可以初始化值

函数定义类似PHP函数的定义,但函数只能通过该类及其实例化的对象访问

 PHP中创建对象

类创建后,可以使用new运算符来实例化该类的对象

$Karry = new Site
$Roy = new Site
$Jackson = new Site

//创建了三个对象,他们都是各自独立的。

调用成员的办法

实例化对象后。可以使用对象调用成员方法,该对象的成员方法只能操作该对象的成员变量

PHP中创建对象

使用new运算符实例化类的对象:

$TFboys = new Karry ();
$TFboys = new Roy ();
$TFboys = new Jackson();

调用成员:

实例化对象后,可以使用该对象调用成员方法,该对象的成员方法只能操作该对象的成员变量:

<?php 
/* 定义一个类为TFboys */
class TFboys { 
	/* 成员变量 */
	var $English;  //在PHP中类的变量使用var来声明
	var $Chinese;
	/* 成员函数 */
	function setEnglish($name1){  //定义一个函数setEnglish
		$this->English = $name1;
	}
	function getEnglish(){
		echo $this->English . PHP_EOL;
	}
	function setChinese($name2){
		$this -> Chinese = $name2;
	}
	function getChinese(){
		echo $this -> Chinese . PHP_EOL;
	}
}

$leader = new TFboys;     //创建类后,使用new实例化该对象
$member1 = new TFboys;
$member2 = new TFboys;

/* 调用成员函数,设置中文名字和英文名字 */
$leader->setEnglish("Karry Wang");
$member1->setEnglish("Roy Wang");
$member2->setEnglish("Jackson Yee");

$leader->setChinese("王俊凯");
$member1->setChinese("王源");
$member2->setChinese("易烊千玺");

//调用成员函数,获取中文名和英文名
$leader->getEnglish();
$member1->getEnglish();
$member2->getEnglish();

$leader->getChinese();
$member1->getChinese();
$member2->getChinese();
?> 

 PHP 构造函数

构造函数是一种特殊的方法,主要用来在创建对象时初始化对象,即为对象成员变量赋初始值,在创建对象的语句中与new运算符一起使用

语法:

void __construct ([ mined $args [,$...]])

上面实例,通过构造放大来初始化$English和$Chinese变量可以这样写:

//这样写就可以不用调用setEnglish和setChinese方法了
function __construct($name1,$name2){
    $this->English = $name1;
    $this->Chinese = $name2;
}

析构函数

与构造函数相反,当对象结束声明周期时,系统自动执行析构函数

语法: 

void __destruct ( void )

实例:

<?php
class MyDestructableClass{
	function __construct() {
		print "构造函数\n";
		$this->name = "MyDestructableClass";
	}
	function __destruct() {
		print "销毁" . $this->name . "\n";
	}
}

$obj = new MyDestructableClass();
?> 

继承

使用关键字extends来继承一个类,PHP不支持多继承

语法: 

class Child extends Parent {
    //代码部份
}

实例:

Child_TFboys继承了TFboys类,并扩展了功能

//子类扩展站点类别
class Child_TFboys extends TFboys {
	var $category;
	
	function setCate($par){
		$this->catgory = $par;
	}
	
	function getCate(){
		echo $this->category . PHP_EOL;
	}

 方法重写 

从父类继承的方法不能够满足子类的要求,可以对其进行改写,这个过程叫方法的覆盖,也叫方法重写

实例:

重写了getEnglish和getChinese方法

<?php
function getEnglish(){
	echo $this->English . PHP_EOL;
	return $this->English;
}

function getChinese(){
	echo $this->Chinese . PHP_EOL;
	return $this->Chinese;
}
?>

访问控制

PHP 对属性或方法的访问控制,是通过在前面添加关键字 public(公有),protected(受保护)或 private(私有)来实现的。

  • public(公有):公有的类成员可以在任何地方被访问。
  • protected(受保护):受保护的类成员则可以被其自身以及其子类和父类访问。
  • private(私有):私有的类成员则只能被其定义所在的类访问。

 

Guess you like

Origin blog.csdn.net/weixin_54438700/article/details/125423491