PHPのクラスの概念を復習したので、後で使いまわしできるようにメモ程度に記載します。
車に関してのテーブルを表示する/classtest1.php
<?php
include 'header.php';//ヘッダーの前半部分の読み込み
echo $header1;
create_title("クラス使いのテスト");//タイトル含むヘッダー後半読み込み
include 'MyClass.php';
$car1 = new Car("111-222", "1.2");
echo "<table border='1'>";
echo "<tr><td>";
echo $car1->getnum();
echo "</td><td>";
echo $car1->getgas();
echo "</td></tr>";
$car2 = new Car("333-444", "3.2");
echo "<tr><td>";
echo $car2->getnum();
echo "</td><td>";
echo $car2->getgas();
echo "</td></tr>";
echo $footer1;
$car3 = new Car2("444-444","1.1","blue","200");
$car4 = new Car2("555-555","2.2","pink","320");
echo "<tr><td>";
echo $car3->getnum();
echo $car3->getcol();
echo "</td><td>";
echo $car3->getpri();
echo "</td></tr>";
echo "<tr><td>";
echo $car4->getnum();
echo $car4->getcol();
echo "</td><td>";
echo $car4->getpri();
echo "</td></tr>";
echo "</table>";
?>
車クラス部分/MyClass.php
<?php
//車のクラス
class Car
{
protected $num = "000-000";
protected $gas = "0.0";
function __construct($nm, $gs)
{
$this->num = $nm;
if($gs >= 0) $this->gas = $gs;
}
function getnum(){ return $this->num; }
function getgas(){ return $this->gas; }
}
//継承した車クラス
class Car2 extends Car
{
private $col = "no";
private $pri = "100";
function __construct($nm, $gs, $cl, $pr)
{
parent::__construct($nm, $gs);
$this->col = $cl;
if($pr >= 0) $this->pri = $pr;
}
function getnum(){ return "ナンバー: ".$this->num."ガソリン: ".$this->gas; }
function getcol(){ return $this->col; }
function getpri(){ return $this->pri; }
}
?>
おまけ、ヘッダーとフッターを使回し/header.php
<?php
//HTMLのヘッダーやフッター部分を簡単に呼び出すphp:include 'header.php';
//ヘッダー部分(DOCタイプ宣言~コンテンツリンクまで):呼び出しecho $header1;
$header1 = <<< HEREDOC
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html" ; charset="utf-8">
<link rel='stylesheet' href='table021.css' type='text/css' />
<link rel='stylesheet' href='clip.css' type='text/css' />
HEREDOC;
//ヘッダー部分(タイトル~ヘッダー終わりbodyまで):呼び出しcreate_title("タイトル記入");
//タイトルを関数のargument実引数 - parameter仮引数
function create_title($title = "無題")
{
echo "<title>{$title}</title>";
echo "</head><body>";
}
//フッター部分(body~html):呼び出しecho $footer1;
$footer1 = <<<HEREDOC
</body></html>
HEREDOC;
?>