PHP tutorial: variables, data types, operators, data structures, conditional judgments, loops, functions and object-oriented

variable

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

variable scope

global variables

Variables defined outside all functions have global scope. To access a global variable in a function, use the global keyword.

<?php
$x=5;
$y=10;
 
function myTest()
{
    
    
    global $x,$y;
    $y=$x+$y;
}
 
myTest();
echo $y; // 输出 15
?>

PHP stores all global variables in an array called $GLOBALS[index]. index holds the name of the variable. This array can be accessed inside the function or used directly to update global variables.

<?php
$x=5;
$y=10;
 
function myTest()
{
    
    
    $GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
} 
 
myTest();
echo $y;
?>

local variables

Variables declared inside a PHP function are local variables and can only be accessed within the function.

Static scope

When a function completes, all of its variables are usually deleted. However, sometimes you want a local variable not to be deleted.

To do this, use the static keyword when you first declare the variable:

<?php
function myTest()
{
    
    
    static $x=0;
    echo $x;
    $x++;
}
 
myTest();
myTest();
myTest();
?>

# 输出结果: 012

echo and print statements

The difference between echo and print:

  • echo - can output one or more strings, separated by commas
  • print - only allows output of a string, the return value is always 1

EOF (heredoc)

<?php
echo <<<EOF
    <h1>我的第一个标题</h1>
    <p>我的第一个段落。</p>
EOF;
// 结束需要独立一行且前后不能空格
?>
  1. It must be followed by a semicolon, otherwise the compilation will fail.
  2. EOF can be replaced by any other character, as long as the end identifier is consistent with the start identifier.
  3. The end mark must occupy a line by itself at the top of the line (that is, it must start from the beginning of the line, and cannot be connected with any blanks or characters).
  4. The start identifier can be without quotes or with single or double quotes. Without quotes, the effect is the same as with double quotes. Embedded variables and escape symbols are interpreted. With single quotes, embedded variables and escape symbols are not interpreted.
  5. When the content requires embedded quotation marks (single quotation marks or double quotation marks), no escape character is needed. Single and double quotation marks are escaped by itself. This is equivalent to the usage of q and qq.

type of data

string

Put any text in single and double quotes

integer

Integers can be specified in three formats: decimal, hexadecimal (prefixed by 0x) or octal (prefixed by 0).

The var_dump() function returns the data type and value of the variable

floating point

Floating point numbers are numbers with a decimal part, or exponential form.

boolean

Boolean type can be TRUE or FALSE.

array

Arrays can store multiple values ​​in one variable.

$cars=array("Volvo","BMW","Toyota");

object

In PHP, objects must be declared. First, you must declare the class object using the class keyword. Classes are structures that can contain properties and methods .

<?php
class Car
{
    
    
  var $color;
  function Car($color="green") {
    
    
    $this->color = $color;
  }
  function what_color() {
    
    
    return $this->color;
  }
}
?> 

In the above example, the PHP keyword this is a pointer to the current object instance and does not point to any other object or class.

operator

Logical Operators

  • with: andor&&
  • or: oror||
  • XOR: xor, if one and only one is true, then return true

Array operators

operator name describe
x + y gather the set of x and y
x == y equal Returns true if x and y have the same key/value pair
x === y identity Returns true if x and y have the same key/value pairs in the same order and type
x != y not equal Returns true if x is not equal to y
x <> y not equal Returns true if x is not equal to y
x !== y Not identical Returns true if x is not equal to y

ternary operator

(expr1) ? (expr2) : (expr3) 

The value when expr1 evaluates to TRUE is expr2, and when expr1 evaluates to FALSE the value is expr3.

As of PHP 5.3, the middle part of the ternary operator can be omitted. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE and expr3 otherwise. Commonly used to determine if the $_GET request contains the user value

<?php
// 如果 $_GET['user'] 不存在返回 'nobody',否则返回 $_GET['user'] 的值
$username = $_GET['user'] ?? 'nobody';
// 类似的三元运算符
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
?>

Combining comparison operators (PHP7+)

The combined comparison operator is called combined comparison operator in English, and its symbol is <=>. It has an image name, called spaceship operator . Combining comparison operators makes it easy to compare two variables.

$c = $a <=> $b
  • If $a > b, b,The value of b , c is 1
  • If $a == b, b,The values ​​of b and c are 0
  • If $a < b, b,The value of b , c is -1

data structure

constant

A constant is an identifier for a simple value. This value cannot be changed in the script. Constants are available throughout the script.

define ( string $name , mixed $value [, bool $case_insensitive = false ] )
  • name: required parameter, constant name, i.e. identifier.
  • value: required parameter, value of constant.
  • case_insensitive: Optional parameter, if set to TRUE, this constant is case-insensitive. The default is case-sensitive.
<?php
// 区分大小写的常量名
define("GREETING", "欢迎访问 Runoob.com");
echo GREETING;    // 输出 "欢迎访问 Runoob.com"
echo '<br>';
echo greeting;   // 输出 "greeting"
?>

super global variable

PHP has several predefined superglobal variables (superglobals), which means that they are available in the entire scope of a script.

$GLOBALS

$GLOBALS is a global combined array containing all variables. The name of the variable is the key of the array.

<?php 
$x = 75; 
$y = 25;
 
function addition() 
{
    
     
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; 
}
 
addition(); 
echo $z; //100
?>

$_SERVER

$_SERVER is an array containing information such as header, path, and script locations. The items in this array are created by the web server. There is no guarantee that every server will offer all items; servers may ignore some, or serve items not listed here.

element/code describe
$_SERVER[‘PHP_SELF’] The file name of the currently executing script, related to document root. For example, using $_SERVER['PHP_SELF'] in a script at http://example.com/test.php/foo.bar will result in /test.php/foo.bar. The FILE constant contains the full path and file name of the current (i.e. containing) file. Starting with PHP version 4.3.0, this variable will contain the script name if PHP is running in command line mode. This variable is not available in previous versions.
$_SERVER[‘GATEWAY_INTERFACE’] The version of the CGI specification used by the server; for example, "CGI/1.1".
$_SERVER[‘SERVER_ADDR’] The IP address of the server where the script is currently running.
$_SERVER[‘SERVER_NAME’] The hostname of the server where the script is currently running. If the script is running on a virtual host, the name is determined by the value set for that virtual host. (eg: www.runoob.com )
$_SERVER[‘SERVER_SOFTWARE’] Server identification string, given in the header information when responding to the request. (eg: Apache/2.2.24)
$_SERVER[‘SERVER_PROTOCOL’] The name and version of the communication protocol used when requesting the page. For example, "HTTP/1.0".
$_SERVER[‘REQUEST_METHOD’] The request method used to access the page; for example, "GET", "HEAD", "POST", "PUT".
$_SERVER[‘REQUEST_TIME’] The timestamp when the request started. Available since PHP 5.1.0. (eg: 1377687496)
$_SERVER[‘QUERY_STRING’] query string (query string), if any, through which page access is performed.
$_SERVER[‘HTTP_ACCEPT’] The content of the Accept: item in the current request header, if it exists.
$_SERVER[‘HTTP_ACCEPT_CHARSET’] The content of the Accept-Charset: item in the current request header, if it exists. For example: "iso-8859-1,*,utf-8".
$_SERVER[‘HTTP_HOST’] The contents of the Host: field in the current request header, if present.
$_SERVER[‘HTTP_REFERER’] Directs the user agent to the address of the page preceding the current page, if one exists. Determined by user agent settings. Not all user agents will set this item, and some also provide the function of modifying HTTP_REFERER. In short, the value is not trustworthy. )
$_SERVER[‘HTTPS’] Set to a non-empty value if the script is accessed via the HTTPS protocol.
$_SERVER[‘REMOTE_ADDR’] The IP address of the user viewing the current page.
$_SERVER[‘REMOTE_HOST’] The hostname of the user browsing the current page. DNS reverse resolution does not depend on the user's REMOTE_ADDR.
$_SERVER[‘REMOTE_PORT’] The port number used on the user's machine to connect to the web server.
$_SERVER[‘SCRIPT_FILENAME’] The absolute path of the currently executing script.
$_SERVER[‘SERVER_ADMIN’] This value specifies the SERVER_ADMIN parameter in the Apache server configuration file. If the script is running on a virtual host, this value is that of that virtual host. (eg: [email protected] )
$_SERVER[‘SERVER_PORT’] The port used by the web server. The default value is "80". If using SSL secure connection, this value is the HTTP port set by the user.
$_SERVER[‘SERVER_SIGNATURE’] A string containing the server version and virtual host name.
$_SERVER[‘PATH_TRANSLATED’] The base path of the file system (not the document root) where the current script is located. This is the result after the server has been imaged from a virtual to real path.
$_SERVER[‘SCRIPT_NAME’] Contains the path to the current script. This is useful when the page needs to point to itself. The FILE constant contains the full path and file name of the current script (such as an include file).
$_SERVER[‘SCRIPT_URI’] URI is used to specify the page to be accessed. For example "/index.html".

$_REQUEST

PHP $_REQUEST is used to collect data submitted by HTML forms.

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
$name = $_REQUEST['fname'];
echo $name;
?>

</body>
</html>

当用户通过点击 “Submit” 按钮提交表单数据时, 表单数据将发送至<form>标签中 action 属性中指定的脚本文件。 $_SERVER['PHP_SELF']说明指定的脚本文件为当前脚本文件。

想了解更多关于html中的表单知识,请点 这里

$_POST

$_POST 被广泛应用于收集表单数据,在HTML form标签的指定该属性:"method=“post”。

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit"》
</form>

<?php
$name = $_POST['fname'];
echo $name;
?>

</body>
</html>

$_GET

$_GET 同样被广泛应用于收集表单数据,在HTML form标签的指定该属性:"method=“get”。

$_GET 也可以收集URL中发送的数据。

  1. 在web服务器的对应目录下创建get_test.php文件
<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>
  1. 用URL向get_test.php文件发送的数据。

在浏览器地址栏输入ip:port/learningPHP/your_dir/get_test.php?subject=PHP&web=runoob.com

得到输出:Study PHP at runoob.com

魔术变量

PHP 向它运行的任何脚本提供了大量的预定义常量。

不过很多常量都是由不同的扩展库定义的,只有在加载了这些扩展库时才会出现,或者动态加载后,或者在编译时已经包括进去了。

有八个魔术常量它们的值随着它们在代码中的位置改变而改变。

变量 解释
LINE 文件中的当前行号
FILE 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名
DIR 文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录
FUNCTION 函数名称
CLASS 类的名称,本常量返回该类被定义时的名字(区分大小写)
TRAIT Trait 的名字
METHOD 类的方法名,返回该方法被定义时的名字(区分大小写)
NAMESPACE 当前命名空间的名称(区分大小写)。此常量是在编译时定义的

字符串变量

  • 字符串连接:

运算符 (.) 用于把两个字符串值连接起来。

 <?php
$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?> 
  • strlen( ):返回字符串的长度(字符数)
  • strpos( ):用于在字符串内查找一个字符或一段指定的文本

如果在字符串中找到匹配,该函数会返回第一个匹配的字符位置。如果未找到匹配,则返回 FALSE。

完整参考手册请点 这里

数组

在 PHP 中,有三种类型的数组:

  • 数值数组 - 带有数字 ID 键的数组
  • 关联数组 - 带有指定的键的数组,每个键关联一个值
  • 多维数组 - 包含一个或多个数组的数组

数值数组

创建数值数组

$cars=array("Volvo","BMW","Toyota");

count( ):获取数组的长度

关联数组

创建关联数组

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

使用指定的键访问数组中对应的键值

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

多维数组

多维数组是包含一个或多个数组的数组。

<?php
// 二维数组:
$cars = array
(
    array("Volvo",100,96),
    array("BMW",60,59),
    array("Toyota",110,100)
);
?>

访问多维数组的值:$sites['runoob'][0]

数组排序

  • sort() - 对数组进行升序排列
  • rsort() - 对数组进行降序排列
  • asort() - 根据关联数组的值,对数组进行升序排列
  • ksort() - 根据关联数组的键,对数组进行升序排列
  • arsort() - 根据关联数组的值,对数组进行降序排列
  • krsort() - 根据关联数组的键,对数组进行降序排列

条件判断

If…Else 语句

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

Switch 语句

<?php
switch (n)
{
    
    
case label1:
    如果 n=label1,此处代码将执行;
    break;
case label2:
    如果 n=label2,此处代码将执行;
    break;
default:
    如果 n 既不等于 label1 也不等于 label2,此处代码将执行;
}
?>

循环

while 循环

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

do…while 语句

首先执行一次代码块,然后在指定的条件成立时重复这个循环

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

for 循环

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

foreach 循环

每进行一次循环,当前数组元素的值就会被赋值给 $value 变量(数组指针会逐一地移动),在进行下一次循环时,您将看到数组中的下一个值。

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

函数

创建 PHP 函数

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

返回值

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

命名空间

PHP 命名空间可以解决以下两类问题:

  • 用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。
  • 为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。

命名空间通过关键字namespace 来声明,命名空间必须是程序脚本的第一条语句

<?php  
// 定义代码在 'MyProject' 命名空间中  
namespace MyProject;  
 
// ... 代码 ...  

可以在同一个文件中定义不同的命名空间代码

<?php
namespace MyProject {
    
    
    const CONNECT_OK = 1;
    class Connection {
    
     /* ... */ }
    function connect() {
    
     /* ... */  }
}

namespace AnotherProject {
    
    
    const CONNECT_OK = 1;
    class Connection {
    
     /* ... */ }
    function connect() {
    
     /* ... */  }
}
?>

全局的非命名空间中的代码与命名空间中的代码组合在一起,只能使用大括号形式的语法。全局代码必须用一个不带名称的 namespace 语句加上大括号括起来

<?php
namespace MyProject {
    
    

const CONNECT_OK = 1;
class Connection {
    
     /* ... */ }
function connect() {
    
     /* ... */  }
}

namespace {
    
     // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

在声明命名空间之前唯一合法的代码是用于定义源文件编码方式的 declare 语句。所有非 PHP 代码包括空白符都不能出现在命名空间的声明之前。

<?php
declare(encoding='UTF-8'); //定义多个命名空间和不包含在命名空间中的代码
namespace MyProject {
    
    

const CONNECT_OK = 1;
class Connection {
    
     /* ... */ }
function connect() {
    
     /* ... */  }
}

namespace {
    
     // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

子命名空间

与目录和文件的关系很象,PHP 命名空间也允许指定层次化的命名空间的名称。因此,命名空间的名字可以使用分层次的方式定义:

<?php
namespace MyProject\Sub\Level;  //声明分层次的单个命名空间

const CONNECT_OK = 1;
class Connection {
    
     /* ... */ }
function Connect() {
    
     /* ... */  }

?>

上面的例子创建了常量 MyProject\Sub\Level\CONNECT_OK,类 MyProject\Sub\Level\Connection 和函数 MyProject\Sub\Level\Connect。

命名空间的使用

PHP 命名空间中的类名可以通过三种方式引用

  • 非限定名称,或不包含前缀的类名称

例如 $a=new foo(); 或 foo::staticmethod();。如果当前命名空间是 currentnamespace,foo 将被解析为 currentnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,则 foo 会被解析为foo。

  • 限定名称,或包含前缀的名称

例如 $a = new subnamespace\foo(); 或 subnamespace\foo::staticmethod();。如果当前的命名空间是 currentnamespace,则 foo 会被解析为 currentnamespace\subnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,foo 会被解析为subnamespace\foo。

  • 完全限定名称,或包含了全局前缀操作符的名称

例如, $a = new \currentnamespace\foo(); 或 \currentnamespace\foo::staticmethod();。在这种情况下,foo 总是被解析为代码中的文字名(literal name)currentnamespace\foo。

面向对象

类的定义

<?php
class phpClass {
    
    
  var $var1;
  var $var2 = "constant string";
  
  function myfunc ($arg1, $arg2) {
    
    
     [..]
  }
  [..]
}
?>

实例:

<?php
class Site {
    
    
  /* 成员变量 */
  var $url;
  var $title;
  
  /* 成员函数 */
  function setUrl($par){
    
    
     $this->url = $par;
  }
  
  function getUrl(){
    
    
     echo $this->url . PHP_EOL;
  }
  
  function setTitle($par){
    
    
     $this->title = $par;
  }
  
  function getTitle(){
    
    
     echo $this->title . PHP_EOL;
  }
}
?>

创建对象

$runoob = new Site;
$taobao = new Site;
$google = new Site;

调用成员方法

$runoob->setTitle( "菜鸟教程" );

构造函数

类似于python 将对象创建为有初始状态 的方法

构造函数是一种特殊的方法。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值

在一个类中定义一个方法作为构造函数

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

析构函数

当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。

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

   function __destruct() {
    
    
       print "销毁 " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

继承

参考 python中的继承

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

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

方法重写

如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。

访问控制

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

links:

https://github.com/Ming-Lian/Memo/blob/master/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%9APHP%E4%B8%80%E5%91%A8%E9%80%9F%E6%88%90.md

Guess you like

Origin blog.csdn.net/a772304419/article/details/133396567