• 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  ?>
     
  • 相关阅读:
    Linux系统安装Apache 2.4.6
    Redhat Server 5.7 安装配置PHP
    ORACLE基本数据类型总结
    Nagios学习实践系列——产品介绍篇
    Linux技术修复
    python的特殊方法:
    python获取对象信息
    python多重继承:
    python多态
    python类的继承
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/9390004.html
Copyright © 2020-2023  润新知