john green php

Object Oriented PHP tutorial

A more comprehensive PHP example

Now lets take a look at an object oriented PHP script. I have commented the script to help readability. Commenting scripts is normally a good idea. It aids readability and helps you to understand your script more easily if you need to return to it later on and have forgotten the inner workings of it.

/**
 * Class Quadruped  base class
 * Class Dog 
 * Class Yorkie 
 * @author John Green <mail@johngreenportfolio.com>
 * @copyright 2011 John C Green 
 */
//base class
class Quadruped{

  private static $_numberOfLegs = 4;//this never changes
  private $_alive;
  //constructor sets the value of $_alive on object creation
  function __construct($isAlive = true){
      $this->_alive = $isAlive;
  }
  public function getHealth(){
      return($this->_alive);
  }
  public function getNumberOfLegs(){
       return self::$_numberOfLegs;
  }
}

//extend the base class
class Dog extends Quadruped{

    public static $subType = "Canine"; //static never changes
    //use string here to construct instead of __constructor call
    protected $_sound = "Barks Woof Woof!";
    //Calling this function echoes out the sound of this class
    function makeSound(){
        echo "<br /><br />$this->_sound <br />";
    }
}
//extend the dog clas and create a yorkie
class Yorkie extends Dog{
   
    private $_breed;
    public $personality;
    public $traits;
    protected $_name;
    private $_breedSize;

    function __construct(){
        $this->_breedSize = "small";
        $this->_breed = "Yorkie";
        $this->personality = "Larger than life";
        $this->traits = array("loyal","Strong willed","fun");
        parent::__construct();//call to parent constructor
    }
    public function setName($name = "unknown"){
        $this->_name = $name;
    }
    public function getName(){
        if( isset( $this->_name ) ){
            $named = "This $this->_breed has been named $this->_name";
            return($named);
        }else{
            return("You need to name this $this->_breed<br /><br />");
        }
    }
}

Now lets take a closer look at this script.

<< Previous Page | Next Page > > Article by J C Green This article was written for non-profit educational purposes. Comments? Suggestions? Rants or raves? E-mail me using the form on this website.