戻る      ①call.php      ②Figure.class.php      ③Square.class.php      ④Triangle.class.php     

《PHP言語 /①call.php》

<html>
<head>
<title>オブジェクト指向入門(ポリモーフィズム)</title>
</head>
<body>
<h1 style="background:#cccccc">オブジェクト指向入門(ポリモーフィズム)</h1>
<?php
function __autoload($name){
require_once($name.".class.php");
}
$objTri=new Triangle();
$objTri->set_width(10);
$objTri->set_height(20);
print("三角形の面積:".$objTri->get_area()."<br />");
$objSqr=new Square();
$objSqr->set_width(10);
$objSqr->set_height(20);
print("四角形の面積:".$objSqr->get_area()."<br />");
?>
</body>
</html>


《PHP言語 /②Figure.class.php》

<?php
abstract class Figure {
private $width;
private $height;
public function __construct(){
$this->width=1;
$this->height=1;
}
public function __destruct(){ /* デストラクタ */ }
public final function get_width() {return $this->width;}
public final function get_height(){return $this->height;}
public final function set_width($width){
if(is_numeric($width)){$this->width=$width;}
}
public final function set_height($height){
if(is_numeric($height)){$this->height=$height;}
}
public abstract function get_area();
}
?>


《PHP言語 /③Square.class.php》

<?php
class Square extends Figure {
public function __construct(){
parent::__construct();
}
public function get_area(){
return $this->get_width() * $this->get_height();
}
}
?>


《PHP言語 /④Triangle.class.php》

<?php
class Triangle extends Figure {
public function __construct(){
parent::__construct();
}
public function get_area(){
return $this->get_width() * $this->get_height() /2;
}
}
?>