これまでに、関数やクラスを作成しました。
一度作成した関数、クラスを様々なプログラムで利用できれば、
作業が楽になります。再利用するコードは別のファイルに分けて
書いておく方がいいです。今回は、クラス宣言のファイルとそれ以外とで
わけてみました。
index.php
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 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="../style.css"> </head> <body> <?php //クラス定義のPHPファイルを読み込む include "class.php"; $user[0] = new User("山田",30,"abc@abcdef.co.jp","12-3456-7890"); echo $user[0]->getName(); echo "<br>"; echo $user[0]->getAge(); echo "<br>"; echo $user[0]->getAdr(); echo "<br>"; echo $user[0]->getTel(); echo "<br>"; ?> </body> </html> |
class.php
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 |
<?php //基本クラスの定義 class Customer { protected $name =""; protected $age =18; function __construct($na,$ag){ $this->name = $na; if( $ag >= 18 && $ag <= 65 ){ $this->age = $ag; }else{ $this->age = -1; } } function getName(){ return $this->name; } function getAge(){ return $this->age; } } //派生クラスの定義 class User extends Customer { private $adr = ""; private $tel =""; function __construct($na,$ag,$ad,$te){ parent::__construct($na,$ag); $this->adr = $ad; $this->tel = $te; } function getName(){return "名前:" . $this->name;} function getAdr(){ return $this->adr;} function getTel(){ return $this->tel;} } ?> |
上記のコードでは、index.phpとclass.phpの2つに分割しています。
index.phpの13行目に
include "class.php";
と書いています。 includeは他のファイルを指定して、
読み込むという処理を行います。ここでは、class.phpを読み込んでいます。
includeの代わりにrequireを使うことができます。
require "class.php";
class.phpが見つからない場合は、includeでは処理を続行しますが、
requireでは処理を中止します。
複数のファイルを読み込む
include,requireを使い複数のファイルを読み込むと、
読込の順番によっては、同じファイルが何度も読み込まれ、
定数や関数定義がおかしくなることが起きてしまいます。
このとき定義死等記述した一度だけ読み込まれるファイルについては、
inclde_once(),require_once()で指定すると、複数回読み込まれる
事態を回避できます。