1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/* ----------------------------------------------------------------------------------
 *  クラス・オブジェクト:インターフェイスの多重継承:ファイルの入出力の例
 *  2015.10.15 作成 yoshi of CXMedia Inc.
 * ----------------------------------------------------------------------------------
 */
header("Content-type:text/plain; charset=UTF-8");
/* --------------------------------------------------------------------------
 * 【インターフェイス】
 * 定義できるのは抽象メソッドのみ (抽象クラスは普通のメソッド定義可能)
 * 抽象メソッドだが「abstract」はいらない
 * アクセス修飾子には「public」しか指定できない→引数の数も名前も完全に一致
 * 直接インスタンスの生成はできない→「実装」:「implements」キーワード使用
 * -------------------------------------------------------------------------- */
/* -------------------
 *   クラスの構成
 * ------------------- */
// インターフェース:DataOutput
interface DataOutput{
    public function 
write($s);
}
// インターフェース:DataInput
interface DataInput{
    public function 
read();
}
// インターフェースの多重継承、カンマ区切りで複数のインターフェイスを指定
// →:DataInput/DataOutput
interface DataIO extends DataOutputDataInput{
    public function 
show($s);
}

// インターフェースを実装
class File implements DataIO{
    
//プロパティ
    
private $path;  //ファイルのパス
    // コンストラクタ
    
function __construct($path){
        
$this->path $path;
    }
    
// インターフェースで宣言されているメソッドを全て定義
    
public function write($str){
        
// ファイル文字列書込
        
return file_put_contents($this->path$str);
    }
    public function 
read(){
        
// ファイル全体文字列読込
        
return file_get_contents($this->path);
    }
    public function 
show($str){
        
// 文字列表示
        
echo $str;
    }
}

/* --------------
 *  クラスの利用
 * -------------- */
// オブジェクト作成:初期データとしてファイルパスを設定
$objFile = new File("data/data_interface.txt");

// 文字列の書き込み
$result $objFile->write("インターフェースのテスト\n");

// 書き込んだ文字列のファイルを読み込んで表示
if($result){
    
$data $objFile->read();
    
$objFile->show($data);
} else {
    echo 
"ファイルに書き込めませんでした\n";
}
?>