第77讲 继承与实现比较 final const

这个具体自己上网查了。。
php 跟 java 一样是单继承
1、implement 接口 可以看做是对类extends的补充,而且接口感觉起来更方便
2、implement 接口可以在不打破类继承的前提下对某个类进行功能性的扩展。

final

  • 1、不希望某个方法被子类重载时,可以用final关键词修饰
  • 2、不希望类被继承时候,可以用final
<?php
/**
    final class A{

    }

    class B extends A{

    }
    print "t";
    //运行会提示:Class B may not inherit from final class (A) 

    */

    class A{
        public $money = -1;
        public function setMoney($money){
            return $this->money = $money*0.8;   
        }
        final public function getMoney(){ //假如 某个方法加了final 那么 B类就无法继承了。否则会报错提示 Cannot override final method A::getMoney() 
            return $this->money;   
        }
    }

    class B extends A{
        /** 
        public function setAge(){

        }

        public function getMoney(){

        }
        */
    }

    $b = new B();
    $b->setMoney(10);
    print $b->getMoney();
?>

final 使用场景:
- 1、安全考虑,类的某个方法不允许修改
- 2、不希望某个类被其他的类继承
final 不能修饰成员属性(变量)

const

image

<?php
    class TestConst{
        const SHUILV = 0.08;
        public function getRat($money){
            return $money*self::SHUILV; //const 访问必须 用 类名::常量名  或者 parent::xx也行
        }

        //public function getConst(){//访问常量不能这么访问 需要使用如上方getRat注释
        //  return $this->SHUILV;
        //}
    }
    class test extends TestConst{
        public function getRat($money){
            return $money*TestConst::SHUILV; //const 访问必须 用 类名::常量名  或者 parent::xx也行
        }
    }
    $test = new test();
    print $test->getRat(100);
    //print $test->getConst();
?>

image

猜你喜欢

转载自blog.csdn.net/u014449096/article/details/78272950