Heim  >  Artikel  >  Backend-Entwicklung  >  php 类和对象_PHP教程

php 类和对象_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:09:46732Durchsuche

php 类和对象

面向对象,是当今编程的主流,对于研发人员,可能对面向对象,多多少少的有一些认识,但是有些不常用的或许不是特别清楚。有时也是很有用的。下面就介绍几点知识。


一、final 关键字的一些知识:


1、final 关键字作为方法是可以被子类继承的。如下面:

class A{
    final function operation(){
        echo 'a';
    }
}

class B extends A{
}


$a=new B();
$a->operation();

result :a


2、final 关键字作为类是不可以继承的,如下:




会有如下错误:

( ! ) Fatal error: Class B may not inherit from final class (A) in D:\wamp\www\examble\index19.php on line 9


3、final 关键字作为的方法不能被子类覆盖,也就是说子类不能有相同的方法,如下

 class A{
    final function operation(){
        echo 'a';
    }
}

 class B extends A{
     function operation(){
        echo 'a';
    }
}


$a=new B();
$a->operation();

会有如下错误:

( ! ) Fatal error: Cannot override final method A::operation() in D:\wamp\www\examble\index19.php on line 12


二、php 多重继承的实现,以下的例子在php 中将会有个致命的错误。

 class A{
    public  function operation(){
        echo 'a';
    }
}

class C{
    public function oper(){
        echo 'c';
    }
}

 class B extends A{
   public  function operation(){
        echo 'a';
    }
}

 class B extends C{
   public function operati(){
      echo 'd';
   }
}


$a=new B();
$a->operation();

( ! ) Fatal error: Cannot redeclare class B in D:\wamp\www\examble\index19.php on line 24


这种形式的多种继承不被允许的。


如果非要实现多种继承,那么只能通过接口的方式实现呢。


 interface Displayable{
   public function display();
 }
 
 interface B{
   public function show();
 }
 
 class A implements Displayable,B{
   public function display(){
     echo 'a';
   }
   public function show(){
     echo 'b';
   }
 }
 
 $ab=new A();
 $ab->display();
 $ab->show();

注意接口的方法都是public,接口的方法只有方法,没有方法体,子类重写接口的方法,接口的方法在子类必须都被重写。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/941436.htmlTechArticlephp 类和对象 面向对象,是当今编程的主流,对于研发人员,可能对面向对象,多多少少的有一些认识,但是有些不常用的或许不是特别清...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn