PHP接口和常量

儘管不能再接口中包含變量,但是可以包含常量。要使用常量,需要用到"作用域解析操作符"即是雙冒號:: ,

示例:使用接口常量的一般格式

$someVariable = InterfaceName::SOME_CONSTANT;

 

演示:

接口文件 IConnectInfo.php

<?php
interface IConnectInfo
{
//    定義常量
    const HOST = "localhost";
    const UNAME = "root";
    const DBNAME = "wqzbxh";
    const PW = "root";
    function testConnection();
}

使用接口文件ConSQL.php

<?php
//引入IConnectInfo接口
include_once('IConnectInfo.php');
Class ConSQL implements IConnectInfo
{
    private $server = IConnectInfo::HOST;
    private $currenDB = IConnectInfo::DBNAME;
    private $user = IConnectInfo::UNAME;
    private $password = IConnectInfo::PW;

    public function testConnection()
    {
        // TODO: Implement testConnection() method.
        try{
            $hookup = new mysqli($this->server,$this->user,$this->password,$this->currenDB);
            if(mysqli_connect_errno()){
                die('connection fail!');
            }
            echo "You are hooked Up Ace!<br/>".$hookup->host_info;
            $hookup->close();
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }
}
$useConstant = new ConSQL();
$useConstant->testConnection();

這裏面接口文件只有一個testconnection方法,但是如果願意接口中也可以只包含變量不包含任何方法;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章