Ну наконец то полиморфизм программирую на
php Описание классов:
class Figure
{
protected $type = '';
public function getArea() {}
public function getPerimeter() {}
public function getType()
{
if ($this->type == '') return 'Неопределен';
else return $this->type;
}
}
class Square extends Figure
{
private $side;
function __construct($a = 0)
{
$this->type = '';
$a = floatval($a);
if ($a > 0)
{
$this->type = 'Square';
$this->side = $a;
}
}
public function getArea()
{
if (!$this->type) return '';
return $this->side * $this->side;
}
public function getPerimeter()
{
if (!$this->type) return '';
return $this->side * 4;
}
}
class Circle extends Figure
{
private $radius;
function __construct($r = 0)
{
$this->type = '';
$r = floatval($r);
if ($r > 0)
{
$this->type = 'Circle';
$this->radius = $r;
}
}
public function getArea()
{
if (!$this->type) return '';
return M_PI * $this->radius * $this->radius;
}
public function getPerimeter()
{
if (!$this->type) return '';
return 2 * M_PI * $this->radius;
}
}
class Triangle extends Figure
{
private $a, $b, $c;
function __construct($a = 0, $b = 0, $c = 0)
{
$this->type = '';
$a = floatval($a); $b = floatval($b); $c = floatval($c);
if (($a > 0 ) && ($b > 0) && ($c > 0))
{
$p = ($a + $b + $c) / 2;
if (($p > $a ) && ($p > $b) && ($p > $c))
{
$this->type = 'Triangle';
$this->a = $a;
$this->b = $b;
$this->c = $c;
}
}
}
public function getArea()
{
if (!$this->type) return '';
$p = ($this->a + $this->b + $this->c) / 2;
return sqrt($p * ($p - $this->a) * ($p - $this->b) * ($p - $this->c));
}
public function getPerimeter()
{
if (!$this->type) return '';
return $this->a + $this->b + $this->c;
}
}
Вызов:
$x = '';
$f = file('file.txt');
foreach ($f as $val)
{
$who = explode(',', trim($val));
$who[] = 0; $who[] = 0; $who[] = 0;
switch ($who[0])
{
case 'circle':
$x[] = new Circle($who[1]);
break;
case 'square':
$x[] = new Square($who[1]);
break;
case 'triangle':
$x[] = new Triangle($who[1], $who[2], $who[3]);
break;
}
}
if ($x)
{
foreach ($x as $v)
{
echo $v->getType(), ' , Площадь=', $v->getArea(), ' , Периметр=', $v->getPerimeter(), '<br>';
}
}
Входные данные file.txt:circle,10
square,20
triangle,5,6,7
circle,4
circle,6
square,7
triangle,13,12,7
Результат:Circle , Площадь=314.15926535898 , Периметр=62.831853071796
Square , Площадь=400 , Периметр=80
Triangle , Площадь=14.696938456699 , Периметр=18
Circle , Площадь=50.265482457437 , Периметр=25.132741228718
Circle , Площадь=113.09733552923 , Периметр=37.699111843078
Square , Площадь=49 , Периметр=28
Triangle , Площадь=41.569219381653 , Периметр=32
P.S. Треугольник задаю сторонами
_____________
There never was a struggle in the soul of a good man that was not hard