PHP 学习笔记

快速了解PHP和PHP Web开发的笔记。

PHP Intro

PHP Syntax

PHP脚本在服务器端执行,返回HTML结果至浏览器。PHP脚本开始于<?php,结束于?>

1
2
3
<?php
// PHP code goes here
?>

PHP中的关键字 (e.g. if, echo, etc) 大小写不敏感,但是变量名大小写敏感。

PHP Variables

PHP中变量以$开头,后面跟着变量名。例如:

1
2
3
4
5
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

命名规则跟其他语言差不多,别搞些奇奇怪怪的就行。

PHP Echo/Print

echo可以有多个参数,print只能一个。echo 输出的速度比 print 快, echo 没有返回值,print有返回值1。其他就差不多。

PHP Data Types

  • String

  • Integer

  • Float (floating point numbers - also called double)

  • Boolean

  • Array (e.g. $cars = array("Volvo","BMW","Toyota");)

  • Object

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?php
    class Car {
    function Car() {
    $this->model = "VW";
    }
    }

    // create an object
    $herbie = new Car();

    // show object properties
    echo $herbie->model;
    ?>
  • NULL

  • Resource

    The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.

    A common example of using the resource data type is a database call.

var_dump()函数可以返回data type和value

PHP Strings

  • strlen()
  • str_word_count()
  • strrev() ->Reverse a String
  • strpos() -> Search For a Text Within a String
  • str_replace()

PHP Numbers

  • is_int()
  • is_integer() - alias of is_int()
  • is_long() - alias of is_int()
  • is_float()
  • is_double() - alias of is_float()
  • is_finite()
  • is_infinite()
  • is_nan()
  • is_numeric() -> check if a string is numeric string
  • The (int), (integer), or intval() function are often used to convert a value (could be string or float) to an integer.

PHP Math

  • pi()
  • min() max()
  • abs()
  • sqrt()
  • round()
  • rand()

PHP Constants

感觉跟java里加了final的变量差不多。用define() 函数来建。

1
2
3
4
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>

PHP Operators

稍微特殊点的运算符就**

==/!=和===/!==的区别:是否比较type

<=> (spaceship)

1
2
3
4
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1

支持自增自减

逻辑运算符:and/or/xor/&&/||/!

PHP String Operators

  • . 连接两个string
  • .= Append str2 to str1

PHP Array Operators

  • +
  • ==
  • ===
  • !=
  • <>
  • !==

PHP Conditional Assignment Operators

  • ?:

  • ?? (e.g. $x = *expr1* ?? *expr2*)

    expr1存在并不为null时返回expr2 反之expr2

PHP Conditional Statements

  • if statement - executes some code if one condition is true
  • if...else statement - executes some code if a condition is true and another code if that condition is false
  • if...elseif...else statement - executes different codes for more than two conditions
  • switch statement - selects one of many blocks of code to be executed

PHP Loops

  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

PHP Arrays

PHP Superglobals

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

PHP Forms

Form handling

1
2
3
4
5
6
7
8
9
10
11
<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

welcome.php looks like:

1
2
3
4
5
6
7
8
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

Form Validation

清理并检查输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data); # 这个很重要
return $data;
}
?>

Check Email and URL

filter_var() function to check whether an email address is well-formed

preg_match() 正则检查URL

Form Required

display error message

1
2
3
4
5
6
7
8
9
10
11
12
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>

check required field

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>

PHP OOP

PHP Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

Constructor & Destructor

__construct() function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");
echo $apple->get_name();
?>

__destructor() function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");
?>

Access Modifiers

  • public

  • protected

  • private

    修饰变量

1
2
3
4
5
6
7
8
9
10
11
12
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}

$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

修饰方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
class Fruit {
public $name;
public $color;
public $weight;

function set_name($n) { // a public function (default)
$this->name = $n;
}
protected function set_color($n) { // a protected function
$this->color = $n;
}
private function set_weight($n) { // a private function
$this->weight = $n;
}
}

$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>

Inheritance

extends 关键词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
  • 子类不能继承父类的protected function

  • 子类可以override父类的方法

  • 父类的final 修饰符可以阻止子类override

Class Constants

1
2
3
4
5
6
7
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}

echo Goodbye::LEAVING_MESSAGE;
?>

和static变量不一样喔,具体区别参考

Abstract Class

An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code.

1
2
3
4
5
6
7
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>

子类继承规则

  • The child class method must be defined with the same name and it redeclares the parent abstract method
  • The child class method must be defined with the same or a less restricted access modifier
  • The number of required arguments must be the same. However, the child class may have optional arguments in addition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
abstract class ParentClass {
// Abstract method with an argument
abstract protected function prefixName($name);
}

class ChildClass extends ParentClass {
// The child class may define optional arguments that are not in the parent's abstract method
public function prefixName($name, $separator = ".", $greet = "Dear") {
if ($name == "John Doe") {
$prefix = "Mr";
} elseif ($name == "Jane Doe") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$greet} {$prefix}{$separator} {$name}";
}
}

$class = new ChildClass;
echo $class->prefixName("John Doe");
echo "<br>";
echo $class->prefixName("Jane Doe");
?>

Traits

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}

class Welcome {
use message1;
}

$obj = new Welcome();
$obj->msg1();
?>

trait和interface不一样喔。具体区别参考

Static Methods

1
2
3
4
5
6
7
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>

To access, use ClassName::staticMethod();

To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected.

Static Properties

1
2
3
4
5
6
7
8
9
10
11
<?php
class pi {
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}

$pi = new pi();
echo $pi->staticValue();
?>

use parent keyword

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
class pi {
public static $value=3.14159;
}

class x extends pi {
public function xStatic() {
return parent::$value;
}
}

// Get value of static property directly via child class
echo x::$value;

// or get value of static property via xStatic() method
$x = new x();
echo $x->xStatic();
?>

参考链接