PHP入门 - 面向对象

类的声明

1
2
3
4
5
6
class Hello {
public function sayello() {
echo 'Hello PHP';
}
}

类的实例化

1
$h = new Hello();

类方法的引用

1
$h->sayello();

类的构造器和外部形参

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
class Man {
/**
* Man constructor.
* @param int $age 年龄
* @param string $name 名字
*/
public function __construct($age, $name) {
echo 'coustruct';
$this->_age = $age;
$this->_name = $name;
}
public function getAge() {
return $this->_age;
}
public function getName() {
return $this->_name;
}
private $_age, $_name;
}

类方法的声明和使用

1
2
3
4
5
6
7
8
class Man {
public static function sayHello() {
echo 'Hello Men';
}
}
Man::sayHello();

PHP静态属性的声明和使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Man {
public function __construct($age, $name) {
echo 'coustruct';
$this->_age = $age;
$this->_name = $name;
Man::$NUM++;
if (Man::$NUM>Man::MAX_NUM) {
throw new Exception('不能创建更多的MAN');
}
}
private $_age, $_name;
private static $NUM = 0;
const MAX_NUM = 100;
}
for ($i=0; $i<200; $i++) {
$m = new Man($i,'Geek');
}

静态的属性和方法是为了描述类的信息,比如以上描述的就是初始人数是0,最大人数是100,成员属性和方法是为了描述类的实例。

类的继承

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
class People {
public function __construct($age, $name, $sex) {
$this->_age = $age;
$this->_name = $name;
$this->_sex = $sex;
}
public function sayHi() {
echo $this->_name.' say hi';
}
private $_age, $_name, $_sex;
}
class Women extends People {
public function __construct($age, $name) {
parent::__construct($age, $name, '女');
}
}
$w = new Women(10, 'Geek');
$w->sayHi();

重写类方法

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
class People {
public function __construct($age, $name, $sex) {
$this->_age = $age;
$this->_name = $name;
$this->_sex = $sex;
}
public function sayHi() {
echo $this->_name.' say hi';
}
private $_age, $_name, $_sex;
}
class Women extends People {
public function __construct($age, $name) {
parent::__construct($age, $name, '女');
}
public function sayHi() {
echo 'women '.$this->getName().' say hi';
}
}
$w = new Women(10, 'Geek');
$w->sayHi();