Adding a Constructor to PriceItem : Constructor « Class « PHP






Adding a Constructor to PriceItem

 
<?php
class Item {
  private $name;

  function __construct( $name="item", $code=0 ) {
    $this->name = $name;
    $this->code = $code;
  }

  function getName () {
    return $this->name;
  }
}

class PriceItem extends Item {
  private $price;

  function __construct( $name, $code, $price ) {
    parent::__construct( $name, $code );
    $this->price = $price;
  }

  function getName() {
    return "(price) ".parent::getName ();
  }
}

$item = new PriceItem ("widget", 5442, 5.20);
print $item->getName ();

?>
  
  








Related examples in the same category

1.Instantiate class by calling the constructor
2.Define and use constructor
3.Define class as constructor parameter
4.Define Constructor for Class
5.A Class with a Constructor
6.Calling the constructor of the parent class
7.Constructors and Destructors
8.Defining an object constructor
9.Creating the Cat constructor
10.Defining object constructors in PHP 4
11.Using the PHP 5 style constructor
12.invoking parent constructors
13.Using Unified Constructors and Destructors
14.Using Default Constructors