Fork me on GitHub

php入门与进阶

php入门与进阶

基本语法

变量

循环

类和对象

魔术方法

__toString

打印类时被调用

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class P{
public $name;
protected $age;
private $height;

function __construct($name, $age, $height)
{
$this->name=$name;
$this->age=$age;
$this->height=$height;
}

public function __get($val)
{
// TODO: Implement __get() method.
return $val;
}

public function __set($name, $value)
{
// TODO: Implement __set() method.
$this->$name=$value;
}

public function __toString()
{
// TODO: Implement __toString() method.
return $this->name.", ".$this->age."岁\n";
}
}

$p1 = new P("张三", 18, 175);
$p2 = new P("李四", 20, 179);

echo $p1;
echo "\n";
echo $p2;


// 输出结果
张三, 18
李四, 20

__get

访问类中的保护和私有变量时被调用, 访问不存在的变量时也会被调用

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class P{
public $name;
protected $age;
private $height;

function __construct($name, $age, $height)
{
$this->name=$name;
$this->age=$age;
$this->height=$height;
}

public function __get($val)
{
// TODO: Implement __get() method.
return $val;
}

public function __set($name, $value)
{
// TODO: Implement __set() method.
$this->$name=$value;
}

public function __toString()
{
// TODO: Implement __toString() method.
return $this->name.", ".$this->age."岁\n";
}
}

$p1 = new P("张三", 18, 175);
$p2 = new P("李四", 20, 179);

echo $p1, $p1->name;
echo "\n";
echo $p2, $p2->age;

// 输出结果
张三, 18
张三
李四, 20
age

__set

设置类中的保护和私有变量时被调用, 设置不存在的变量时也会调用

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class P{
public $name;
protected $age;
private $height;

function __construct($name, $age, $height)
{
$this->name=$name;
$this->age=$age;
$this->height=$height;
}

public function __get($val)
{
// TODO: Implement __get() method.
return $val;
}

public function __set($name, $value)
{
// TODO: Implement __set() method.
var_dump($name, $value);
$this->$name=$value;
}

public function __toString()
{
// TODO: Implement __toString() method.
return $this->name.", ".$this->age."岁\n";
}
}

$p1 = new P("张三", 18, 175);
$p2 = new P("李四", 20, 179);


echo $p1;
$p1->name='王五';
echo $p1;

$p1->age=15;
echo $p1;

$p1->ss = "not found";
echo $p1;


// 输出结果
张三, 18
王五, 18

string(3) "age"
int(15)

王五, 15

string(2) "ss"
string(9) "not found"
王五, 15

__unset

__call

访问不存在的方法时被调用

__callStatic

访问不存在的静态方法时被调用

__invoke

把对象变成方法使用, 对比python中的__call__

网络编程

TCP

UDP

框架

Yii

ThinkPHP

Lavarel

##

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%