美文网首页
类的继承

类的继承

作者: laochonger | 来源:发表于2018-04-11 16:52 被阅读0次

    <?php
    class B extends A{
    public $attribute2;
    function operation2(){

    }
    

    }
    //用关键词extends来指明其继承关系
    //上面代码创建了一个名为B的类,他继承了前面定义的类A

    //如果A具有如下的声明
    class A{
    public $attribute;
    function operation1(){

    }
    

    }
    //则如下的所有对类B对象操作和属性都是有效的
    $a = new B();
    $b ->operation1();
    $b ->attribute1 = 10;
    $b ->operation2();
    $b = attribute2 = 10;

    //因为类B派生于类A,所以可以使用操作operation1()和属性$attribute1
    //尽管这些操作和属性是在类A里声明的。

    //继承是单向的

    // 通过继承使用private和protected访问修饰符控制可见性
    //如果一个属性或方法被定义为private,它将不能被继承,即私有操作不能被子类使用
    //如果一个属性或方法被定义为protected。它将在类外部不可见,但是可以被继承,可以在子类中被使用

    // 重载
    class A{
    public $attribute = "default value";
    function operation(){
    echo "something<br />";
    echo "the value of $attribute is ".$this->attribute."<br />";
    }
    }

    //现在,如果需要改变$attribute的默认值,并未operation()操作提供新的功能,可以创建类B,它重载了$attribute和operation()方法
    class B extends A{
    public $attribute = "different value";
    function operation(){
    echo "something else<br />";
    echo "the value of $attribute is ".$this->attribute."<br />";
    }
    }

    //声明类B并不会影响类A的初始定义
    //如果不使用替代,一个子类将继承超类的所有属性和操作,如果子类提供了替代定义,替代定义将有优先级并且重载厨师定义

    parent::opreation();

    //虽然调用了父类结构,但是将使用当前类的属性值
    //继承可以是多重的

    //php提供了final关键字,可以使得函数不能被重载

    class B extends A{
    public $attribute = "different value";
    final function operation(){
    echo "something else<br />";
    echo "the value of $attribute is ".$this->attribute."<br />";
    }
    }

    //也可以用于禁止一个类被继承

    //php中每个类仅仅能继承一个父类,但是父类还以当作子类已经继承过它的父类
    //可以C->B->A
    //B->A C->A
    //不可以 C->B C->A

    相关文章

      网友评论

          本文标题:类的继承

          本文链接:https://www.haomeiwen.com/subject/chjzhftx.html