php中final关键字

1.final关键字(不能修饰属性,即变量)

a.希望一个类不被其他类来继承(出于安全性)

案例1

<?php
  final  class A
  {
 
  }
  class B EXTENDS A //此用法为错误
  {
  ECHO "OK";
  }
?>


结果:

Parse error: syntax error, unexpected T_ECHO, expecting T_FUNCTION in E:\Software_default\wamp_wwwroot\interface\interface05.phpon line 8

 

来自 <http://localhost/interface/interface05.php>

 

b.希望某个方法,不被子类改写,用final,对比案例2,案例3结果

 

案例2:没有重写

<?php
  class A
  {
	  public function getrate($salary)
	  {
		  return $salary;
	  }
	  
  }
  class B extends A 
  {
    
  }
  $b=new B();
  echo $b->getrate(100);
?>


结果

100

 

来自 <http://localhost/interface/interface06.php>

 

 

案例3:覆盖

<?php
  class A
  {
  public function getrate($salary)
  {
  return $salary;
  }
 
  }
  class B extends A 
  {
    public function getrate($salary)
  {
  return $salary*100;
  }
  }
  $b=new B();
  echo $b->getrate(100);
?>


结果

10000

 

来自 <http://localhost/interface/interface07.php>

 

 

案例4:禁止重写

<?php
  class A
  {
  final public function getrate($salary)
  {
  return $salary;
  }
 
  }
  class B extends A //
  {
    public function getrate($salary)
  {
  return $salary*100;
  }
  }
  $b=new B();
  echo $b->getrate(100);
?>


结果:

Fatal error: Cannot override final method A::getrate() in E:\Software_default\wamp_wwwroot\interface\interface08.phpon line 16

 

来自 <http://localhost/interface/interface08.php>

 

 


发布了19 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wmin510/article/details/51457469