Blogger Information
Blog 41
fans 0
comment 0
visits 30982
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP的接口和抽象类
陈强
Original
687 people have browsed it

接口

  • 声明接口 :interface
  1. interface iApp
  2. {
  3. //声明常量
  4. const NAME = '用户管理系统';
  5. //静态成员 公共抽象方法
  6. public static function getUser(...$args);
  7. //构造方法
  8. public function __construct(...$args);
  9. }
  • 实现类/工作类 :implements
  1. class App implements iApp
  2. {
  3. //实现静态方法
  4. public static function getUser(...$args)
  5. {
  6. return print_r($args,true);
  7. }
  8. //实现构造方法
  9. public function __construct(...$args)
  10. {
  11. return $this->getUser();
  12. }
  13. }
  • 调用
  1. //实例化实现类
  2. $app = new App();
  3. //用接口调用常量
  4. echo iApp::NAME;
  5. //用类调用静态成员
  6. echo App::getUser(['name'=>'jack','age'=>28]);
  • 接口继承
  1. interface iApp
  2. {
  3. //声明常量
  4. const NAME = '用户管理系统';
  5. //静态成员 公共抽象方法
  6. public static function getUser(...$args);
  7. //构造方法
  8. public function __construct(...$args);
  9. }
  10. interface iUser {
  11. //声明常量
  12. const USERNAME = 'admin';
  13. }
  14. //可以继承多个接口,用逗号隔开
  15. interface iLogin extends iApp,iUser
  16. {
  17. public function userpwd(string $arg);
  18. }

抽象类

  1. abstract class Model
  2. {
  3. public function login() {}
  4. abstract public function __construct($name);
  5. }
  6. // 抽象类必须通过它的子类才可以使用
  7. class userModel extends Model
  8. {
  9. private $name;
  10. // 抽象类的实现类(子类)必须将抽象类的抽象方法实现
  11. public function __construct($name)
  12. {
  13. $this->name = $name;
  14. }
  15. public function login()
  16. {
  17. echo '恭喜'. $this->name . '注册成功';
  18. }
  19. }
  20. $user = new userModel('jack');
  21. echo $user->login();
  22. //输出 : 恭喜jack注册成功

静态继承上下文

父类静态方法可以被子类继承和重写

  1. class Getuser
  2. {
  3. public static function user(){
  4. return '这里是父类' .__METHOD__;
  5. }
  6. public static function goods(){
  7. return static::user();
  8. }
  9. }
  10. class Myuser extends Getuser
  11. {
  12. public static function user(){
  13. return '这里是子类' . __DIR__;
  14. }
  15. }
  16. $myuser = new Myuser();
  17. echo Myuser::user() .'<br>';
  18. echo Myuser::goods();

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:接口好好看看, 以后你自己可以不写, 但肯定会天天用到
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post