Interface, Inheritence using php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
s1auk14
Forum Newbie
Posts: 15
Joined: Mon Nov 02, 2009 8:29 am

Interface, Inheritence using php

Post 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);
 
?>
s1auk14
Forum Newbie
Posts: 15
Joined: Mon Nov 02, 2009 8:29 am

Re: Interface, Inheritence using php

Post by s1auk14 »

Anybody?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Interface, Inheritence using php

Post 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.
Post Reply