php课程 12-39 继承中parent的作用是什么

php课程 12-39 继承中parent的作用是什么

一、总结

一句话总结:PHP5中使用parent::来引用父类的方法。parent:: 可用于调用父类中定义的成员方法。 parent::的追溯不仅于直接父类。

 

1、对象链实例?

1.document.body.style.background='#f00';
2.$('.img').show().click(func);
3.$obj->show()->say()->eat()->click();

 

2、php对象链如何实现?

每个方法中都把$this对象返回了

14     function eat(){
15         echo '<h1>eat</h1>'; 16 return $this; 17  }

 

3、php中的类如何直接调用类里面的方法?

是双冒号调用

类只能去直接调用没有$this(对象的属性,比如方法中要用到属性)的方法,因为没有对象,也就是没有$this
Person::say()

 

4、如何解决父亲儿子继承父亲之后构造函数重用不够彻底的情况?

在儿子的构造函数中调用父亲的构造函数
parent::__construct($n,$a,$s);

 

 

二、继承中parent的作用是什么

1、相关知识

构造方法:
1.__construct();
2.Person(); #如果有一个方法名字与类名相同,则该方法为构造方法

析构方法:
1.__destruct();
2.析构时变量从下往上删

对象链:
1.document.body.style.background='#f00';
2.$('.img').show().click(func);
3.$obj->show()->say()->eat()->click();

属性的作用域:
1.属性的作用域
2.局部变量的作用域

通过类名直接调用方法:
Person::say();  #前提是say方法中不能出现$this本对象

继承特性:
class It extends Person{
    //代码
}

继承关键字:
1.extends
2.parent

封装特性:
1.public
2.protected
3.private

 

 

2、代码

extends中parent的作用

 1 <?php 
 2 class Person{
 3     public $name;
 4 
 5     public function __construct($n,$a,$s){
 6         $this->name=$n;
 7         $this->age=$a;
 8         $this->sex=$s;
 9     }
10 
11     public function say(){
12         echo "<h1>我的名字是: $this->name</h1>";
13     }
14 }
15 
16 class It extends Person{
17     public $program;
18 
19     public function __construct($n,$a,$s,$p){
20         parent::__construct($n,$a,$s);
21         $this->program=$p;
22     }
23 
24     public function develop(){
25         echo "<h1>{$this->name}正在开发{$this->program}项目</h1>";
26     } 
27 }
28 
29 $obj=new It('小金',20,'nan','PHP');
30 
31 $obj->say();
32 $obj->develop();
33  ?>

 

对象链实现原理

 1 <?php 
 2 class Person{
 3     public $name;
 4 
 5     function __construct($n){
 6         $this->name=$n;
 7     }
 8 
 9     function say(){
10         echo '<h1>say</h1>';
11         return $this;
12     }
13 
14     function eat(){
15         echo '<h1>eat</h1>';
16         return $this;
17     }
18 
19     function sleep(){
20         echo '<h1>sleep</h1>';
21     }
22 }
23 
24 //对象链原理
25 $obj=new Person('user1');
26 $obj->say()->eat()->sleep();
27  ?>

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/Renyi-Fan/p/9390004.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值