background image

2.

$ncart

 = 

new

 Named_Cart; 

// 

 

新建一个有名字的购物车

 

3.

$ncart

->set_owner(

"kris"

); 

// 

 

给该购物车命名

 

4.

print 

$ncart

->owner; 

// 

 

输出该购物车主人的名字

 

5.

$ncart

->add_item(

"10"

, 1); 

// 

 

(从购物车类中继承来的功能)

 

6. ?>  

 

这个也可以叫做 父-子 关系。创建一个类,父类,并使用 extends 来创建一个基

于父类的新类:子类。甚至可以使用这个新的子类来创建另外一个基于这个子类的类。

Note:

 

类只有在定义后才可以使用!如果需要类 Named_Cart 

 

继承类 Cart,必须首先定

 

义 Cart 

 

类。如果需要创建另一个基于 Named_Cart 

 

类的 Yellow_named_cart 类,必

 

须首先定义 Named_Cart 类。简捷的说:类定义的顺序是非常重要的。

1.

class

 Person{  

2.

protected

 

$name

;

//protected 保护的权限,

 

在子类可以访问,外部不能访问

 

3.

protected

 

$age

;  

4.

protected

 

$sex

;  

5.

function

 __construct(

$name

,

$age

,

$sex

){  

6.

$this

->name=

$name

;

//当使用 this 时,就算 name

 

没有声明,也会再次声明一个

 

7.

$this

->age=

$age

;  

8.

$this

->sex=

$sex

;  

9.

echo 

"###############"

;  

10. }  

11.

public

 

function

 say(){  

12.

echo 

"我的名字:{$this->name},我的年龄{$this->age}:,我的性别:{$this-

>sex}<br/>"

;  

13. }  

14.

protected

 

function

 eat(){  

15.

echo 

"wwwwwwwwwwwwwwwwwwwww<br>"

;  

16. }  

17.

function

 run(){  

18. }  

19.

protected

 

$name

;

//protected 保护的权限,

 

在子类可以访问,外部不能访问

 

20.

protected

 

$age

;  

21.

protected

 

$sex

;  

22. }  

23.

//

 

继承

 

24.

class

 Student 

extends

 Person{  

25.

var

 

$school

;  

26.

function

 __construct(

$name

,

$age

,

$sex

,

$school

){  

27.

parent::__construct();

//

 

调用父类的构造方法

 

28.

$this

->school=

$school

;  

29. }  

30.

//重载 say()方法,

 

进行扩展