PHP Program to Polymorphic Areas with Explanation
PHP
Medium
PHP OOP Basics
32 views
1 min read
100 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around area, type, line. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Types: C r for circle, S a for square. Print area for each shape with 2 decimals.
Input Format
First n. Next n lines type value.
Output Format
n lines areas.
Constraints
n
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
abstract class Shape{ abstract function area(); }
class Circle extends Shape{
private $r;
function __construct($r){ $this->r=$r; }
function area(){ return 3.141592653589793*$this->r*$this->r; }
}
class Square extends Shape{
private $a;
function __construct($a){ $this->a=$a; }
function area(){ return $this->a*$this->a; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$n=intval($inputLines[0]);
$output=[];
for($i=1;$i<=$n;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''));
$t=$tokens[0] ?? '';
$v=floatval($tokens[1] ?? 0);
if($t==='C') $sh=new Circle($v);
else $sh=new Square($v);
$output[] = number_format($sh->area(),2,'.','');
}
echo implode(PHP_EOL,$output);
?>
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Types: C r for circle, S a for square. Print area for each shape with 2 decimals.
Input / Output
Input
First n. Next n lines type value.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
<?php
abstract class Shape{ abstract function area(); }
class Circle extends Shape{
private $r;
function __construct($r){ $this->r=$r; }
function area(){ return 3.141592653589793*$this->r*$this->r; }
}
class Square extends Shape{
private $a;
function __construct($a){ $this->a=$a; }
function area(){ return $this->a*$this->a; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$n=intval($inputLines[0]);
$output=[];
for($i=1;$i<=$n;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''));
$t=$tokens[0] ?? '';
$v=floatval($tokens[1] ?? 0);
if($t==='C') $sh=new Circle($v);
else $sh=new Square($v);
$output[] = number_format($sh->area(),2,'.','');
}
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!