Home / PHP/MySQL Tutorials / Object Oriented PHP / Archive by category 'Php OOPS Examples'

Php OOPS Examples

Using Default Constructors

<?php
class Dog {
    function __construct($name='No-name', $breed='breed unknown', $price = 15) {
        $this->name = $name;
        $this->breed = $breed;
        $this->price = $price;
    }
}
$aDog = new Dog();
$tweety = new Dog('A', 'a'); printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$aDog->name, $aDog->breed, $aDog->price); $tweety->price = 24.95; printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$tweety->name, $tweety->breed, $tweety->price);
?>

Using Inheritance To Efficiently Represent Various Vehicle Types

<?
class Vehicle {
     var $model;
     var $current_speed;     function setSpeed($mph) {
          $this->current_speed = $mph;
     }     function getSpeed() {
          return $this->current_speed;
     }
}class Auto extends Vehicle {
    var $fuel_type;    function setFuelType($fuel) {
          $this->fuel_type = $fuel;
    }     function getFuelType() {
          return $this->fuel_type;
     }}class Airplane extends Vehicle {
     var $wingspan;     function setWingSpan($wingspan) {
          $this->wingspan = $wingspan;
     }     function getWingSpan() {
          return $this->wingspan;
     }
}
?>

Using Private And Public In Classes

<?php
     class myPHP5Class {
          private $my_variable;
          public function my_method($param) {
               echo "my_method($param)!\n";
               echo "my variable is: ";
               echo "{$this->my_variable}\n";
          }
     }     $myobject = new myPHP5Class();     $myobject->my_method("MyParam");     $myobject->my_variable = 10;
?>

Using __Sleep() And __Wakeup() For Objects

<?php
     class UserClass {
          public $sessionID;
          public $username;          public function __sleep() {
               session_destroy();
               return array("username");
          }
          public function __wakeup() {
               session_start();
               $this->sessionId = session_id();
          }
     }
     session_start();
     $user = new UserClass;
     $user->sessionId = session_id();
     $seralized_user = serialize($user);     unset($user);
     $user = unserialize($serialized_user);
?>

Using Static Methods And Properties To Limit Instances Of A Class (Php 5 Only)

<?phpclass Shop {
  private static $instance;
  public $name="shop";  private function ___construct() {
  }  public static function getInstance() {
    if ( empty( self::$instance ) ) {
    self::$instance = new Shop();
    }
    return self::$instance;
  }
}$first = Shop::getInstance();
$first-> name="A";$second = Shop::getInstance();
print $second -> name;
?>

Using The -> And :: Operators To Call Hypnotize

<?php
    class Cat {
    }class MyCat extends Cat {
    function MyCat(  ) {
    }
    public static function hypnotize(  ) {
      echo ("The cat was hypnotized.");
      return;
    }
}MyCat::hypnotize(  );$h_cat = new MyCat(  );
$h_cat->hypnotize(  );

Using The __Autoload() Function

<?php
     function __autoload($class) {
          $files = array('MyClass' => "/path/to/myClass.class.php",
                         'anotherClass' => "/path/to/anotherClass.class.php");
          if(!isset($files[$class])) return;
          require_once($files[$class]);
     }
     $a = new MyClass;
     $b = new anotherClass;
?>

Using The __Call() Method

<?php
     class ParentClass {
          function __call($method, $params) {
               echo "The method $method doesn't exist!\n";
          }
     }
     class ChildClass extends ParentClass {
          function myFunction() {
          }
     }
     $inst = new ChildClass();
     $inst->nonExistentFunction();
?>

Using The __Clone() Method

<?php
     class myObject {
          public $var_one = 10;
          public $var_two = 20;
          function __clone() {
                    $this->var_two = 0;
          }
     }
     $inst_one = new myObject();
     $inst_two = clone $inst_one;
     var_dump($inst_one);
     var_dump($inst_two);
?>

Using The Clone Statement

<?php
     class Integer {
          private $number;
          public function getInt() {
               return (int)$this->number;
          }
          public function setInt($num) {
               $this->number = (int)$num;
          }
     }
 
     $class_one = new Integer();
     $class_one_copy = clone $class_one;
?>

Using The Extends Keyword To Define A Subclass

<?php
class Cat {
    var $age;    function Cat($new_age){
        $this->age = $new_age;
    }
    function Birthday(  ){        $this->age++;
    }
}
class MyCat extends Cat {
    function MyCat(  ) {
    }
    function sleep(  ) {
        echo("Zzzzzz.<br />");
    }
}
$fluffy=new MyCat(  );
$fluffy->Birthday(  );
$fluffy->sleep(  );
echo "Age is $fluffy->age <br />";
?>

Using The Parent Construct

<?php
class Cat {
    var $age;    function Cat($new_age){
        $this->age = $new_age;
    }
    function Birthday(  ){
        $this->age++;
    }
    function Eat(  ){        echo "Chomp chomp.";
    }
    function Meow(  ){        echo "Meow.";
    }
}class MyCat extends Cat {
    function MyCat(  ) {
    }
    function eat(  ) {
        parent::eat(  );
        $this->meow(  );
    }
}
?>

Using The Php 5 Style Constructor

<?php
class Cat {
  Function __constructor(  ){
  }
}
?>

Using The __Tostring() Method

<?php
    class User {
            private $username;
            function __construct($name) {
                    $this->username = $name;
            }
            public function getUserName() {
                    return $this->username;
            }
            function __toString() {
                    return $this->getUserName();
            }
    }
    $user = new User("john");
    echo $user;
?>

Using Type Hinting With Interfaces

<?php
     interface printable {
          public function printme();
     }     abstract class Number {
          private $value;
          abstract public function value();
          public function reset() {
               $this->value = NULL;
          }
     }     class Integer extends Number implements printable {
          private $value;
          function __construct($value) {
               $this->value = $value;
          }
          public function getValue() {
               return (int)$this->value;
          }
          public function printme() {
               echo (int)$this->value;
          }
     }     function printNumber(printable $myObject) {
          $myObject->printme();
     }
     $inst = new Integer(10);
     printNumber($inst);
?>

Using Unified Constructors And Destructors

<?php
     class SimpleClass {
          function __construct($param) {
               echo "Created a new instance of SimpleClass!";
          }
          function __destruct() {
               echo "Destroyed this instance of SimpleClass";
          }
     }
     $myinstance = new SimpleClass("value");
     unset($myinstance);
?>

Var_Dump A Class

 
    <?php
class Person {
    private $name;
    private $age;
    private $id;        function __construct( $name, $age ) {
        $this->name = $name;
        $this->age = $age;
    }    function setId( $id ) {
        $this->id = $id;
    }
 
    function getId(){
        echo "get id method";
    }
 
    function __clone() {
        $this->id = 0;
    }
}var_dump( new Person("A",10) );?>

__Wakeup() Is Called By Unserialize().

<?
class apple {
  var $frozen = 0;
  function ___sleep( ) {
    $this->frozen++;
    return array_keys( get_object_vars( $this) );
  }
  function __wakeup( ) {
      print $this->frozen." time(s)";
  }
}
$app = new apple ( );
$stored = serialize( $app );
print $stored;
$new_app = unserialize( $stored );?>

Properties And Methods Marked As Protected Are Accessible Only Through The Object That Owns Them

<?
    class Dog {
            public $Name;
            private function getName( ) {
                    return $this->Name;
            }
    }    class Poodle extends Dog {
            public function bark( ) {
                    print "'Woof', says " . $this->getName( );
            }
    }    $poppy = new Poodle;
    $poppy->Name = "Poppy";
    $poppy->bark( );
?>

Properties Get Demo

 
    <?php
class Person {
    function __get( $property ) {
        $method = "get{$property}";
        if ( method_exists( $this, $method ) ) {
            return $this->$method();
        }
    }
 
    function getName() {
        return "Joe";
    }
 
    function getAge() {
        return 31;
    }
}$p = new Person();
print $p->name;
?>