尽管不能再接口中包含变量,但是可以包含常量。要使用常量,需要用到"作用域解析操作符"即是双冒号:: ,
示例:使用接口常量的一般格式
$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方法,但是如果愿意接口中也可以只包含变量不包含任何方法;