Home > php教程 > php手册 > body text

php 类和对象

WBOY
Release: 2016-06-13 09:17:10
Original
1310 people have browsed it

php 类和对象

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


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


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

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

class B extends A{
}


$a=new B();
$a->operation();
Copy after login

result :a


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


Copy after login


会有如下错误:

( ! ) 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();
Copy after login

会有如下错误:

( ! ) 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();
Copy after login

( ! ) 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();
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!