Page 1 of 1

Interface, Inheritence using php

Posted: Mon Nov 02, 2009 8:35 am
by s1auk14
Hi all, currently i am learning about objects in php. I have just did some testing. Below are the code. Can anybody comment them? Thank you.

Code: Select all

<?php
interface area2D{
  public function get_area();
}
 
class shape2D{
  private $length;
  private $width;
 
  function __construct( $slength = 1, $swidth = 1 ){
    $this->set_length( $slength );
    $this->set_width( $swidth );
  }
 
  public function set_length( $slength ){
    $this->length = $slength;
  }
 
  public function set_width( $swidth ){
    $this->width = $swidth;
  }
 
  public function get_length(){
    return $this->length;
  }
 
  public function get_width(){
    return $this->width;
  }
}
 
class rectangle extends shape2D implements area2D{
  function __construct( $rlength, $rwidth ){
    parent::__construct( $rlength, $rwidth );
  }
 
  public function get_area(){
    return $this->get_length() * $this->get_width();
  }
}
 
class triangle extends shape2D implements area2D{
  function __construct( $tlength, $theight ){
    parent::__construct( $tlength, $theight );
  }
 
  public function get_area(){
    return 0.5 * $this->get_length() * $this->get_width();
  }
}
 
function show_area( shape2D $shape = null ){
  if ( $shape instanceof shape2D )
    echo $shape->get_area();
  else
    echo 'Not identified shape input';
}
 
$rec = new rectangle( 6, 10 );
show_area($rec);
$tri = new triangle ( 5, 20 );
show_area($tri);
 
?>

Re: Interface, Inheritence using php

Posted: Mon Nov 02, 2009 9:10 pm
by s1auk14
Anybody?

Re: Interface, Inheritence using php

Posted: Mon Nov 02, 2009 10:19 pm
by requinix
It doesn't make sense (to me) to use an interface for area. Area is a part of the 2D shape itself - it's not like it's extra functionality.

Then for your function, $shape must be a shape2d because you defined it to be. However you also set the default for it (which doesn't make sense) to be null, so all in all $shape is either a shape2d or null. Can't be anything else. Just FYI.