Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / PHP契约式编程

先复习一下面向对象编程中的两个重要元素:抽象类和接口抽象类当类中有一个方法为抽象方法,该类就应该定义为抽象类继承一个抽象类,应该实现其所有抽象方法推荐阅读:生产环境实用之LNMP架构的编译安装+SSL加密实现 http://www.linuxidc.com/Linux/2013-05/85099.htmLNMP 全功能编译安装 for CentOS 6.3笔记 http://www.linuxidc.com/Linux/2013-05/83788.htmCentOS 6.3 安装LNMP (PHP 5.4,MyySQL5.6) http://www.linuxidc.com/Linux/2013-04/82069.htm在部署LNMP的时候遇到Nginx启动失败的2个问题 http://www.linuxidc.com/Linux/2013-03/81120.htmUbuntu安装Nginx php5-fpm MySQL(LNMP环境搭建) http://www.linuxidc.com/Linux/2012-10/72458.htm《细说PHP》高清扫描PDF+光盘源码+全套教学视频 http://www.linuxidc.com/Linux/2014-03/97536.htm例:<?php
abstract class car{
    protected $name;
    protected $speed;
   
    public function __construct($name, $speed){
          $this->name=$name;
          $this->speed=$speed;
    }
   
    abstract function run();
   
    public function __get($k){
          if(in_array($k, array("name"))){
              //如果访问的属性是不允许的,抛出error级别错误
              trigger_error ( "禁止访问私有成员 : ".$k , E_USER_ERROR  ) ;
              return ;
          }
       
          return $this->$k;
    }
}接口
 
接口定义了一系列必要的操作,实现接口的类必须实现接口的方法
 
例:people.interface.php
<?php
interface people{
   
    //定义say方法,时所有派生类必须实现
    public function say();
   
}
work.class.php
<?php
include "people.interface.php";
class worker implements people{    private $name;
    private $age;
   
    public function __construct($name, $age){
          $this->name=$name;
          $this->age=$age;
    }
   
    //实现接口定义方法
    public function say(){
          echo $this->name.", age is ".$age." <br />";
    }
   
    public function __get($k){
          if($k=="name"){
              //如果访问的属性是不允许的,抛出error级别错误
              trigger_error ( "禁止访问私有成员 : ".$k , E_USER_ERROR  ) ;
              return;
          }
          return $this->$k;
    }
}更多详情见请继续阅读下一页的精彩内容: http://www.linuxidc.com/Linux/2014-05/101905p2.htm