Showing posts with label Constructor. Show all posts
Showing posts with label Constructor. Show all posts

Friday 27 July 2012

PHP Constructor


A Class with a Constructor

<?php
 class Item {
   var $name;

   function Item( $name="") {
     $this->name = $name;
   }

   function setName( $n) {
     $this->name = $n;
   }

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

 $item = new Item("5");
 print $item->getName ();
?>

Output :

5

Invoking parent constructors

<?php
class Staff
{
    function __construct()
    {
        echo "<p>Staff constructor called!</p>";
    }
}

class Manager extends Staff
{
    function __construct()
    {
        parent::__construct();
        echo "<p>Manager constructor called!</p>";
    }
}

$employee = new Manager();
?>

Output :

Staff constructor called!
Manager constructor called!