. PHP Design Patterns . PHP Design Patterns PHP OO Class Basics

PHP Design Patterns PHP OO Class Basics

About OO PHP Class Basics


Here is an example of creating a very simple class called OOPHPClass. The class has one variable, and functions to "set" and "get" that variable.





OOPHPClass.php

//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved

  //OOPHPClass - a simple OO PHP Class
  
  class OOPHPClass {
    
    //this is a private variable, and can only be accessed by this class
    private $instanceName;
    
    //a constructor is called when an "instance" of a class is created
    function __construct() {      
      $this->instanceName = 'default';
    }  
    
    public function getName() {
      return $this->instanceName;
    }  
    
    //the this-> part referers to the variable specific to one instance
    public function setName($nameIn) {
      $this->instanceName = $nameIn;
    }    
  
  }

download source, use right-click and "Save Target As..." to save with a .php extension.


testOOPHP.php


//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved

  include_once('OOPHPClass.php');

  define('BR', '<'.'BR'.'>');

  echo 'TESTING OOPHPClass'.BR;
  echo BR;
  
  echo 'test 1 - create a class'.BR;
  $classOne = new OOPHPClass();
  echo 'default name: '.$classOne->getName();
  echo BR;
  $classOne->setName("Harold");
  echo 'name after set: '.$classOne->getName();
  echo BR.BR;

  echo 'test 2 - create another class'.BR;
  $classTwo = new OOPHPClass();
  $classTwo->setName("Wilma");
  echo $classTwo->getName();
  echo BR.BR;

  echo 'test 3 - show both classes'.BR;
  echo 'Class One Name: '.$classOne->getName();
  echo BR;
  echo 'Class Two Name: '.$classTwo->getName();
  echo BR.BR;

  echo 'END TESTING OOPHPClass'.BR;

download source, use right-click and "Save Target As..." to save with a .php extension.


output of testOOPHP.php

TESTING OOPHPClass

test 1 - create a class default name: default name after set: Harold

test 2 - create another class Wilma

test 3 - show both classes Class One Name: Harold Class Two Name: Wilma

END TESTING OOPHPClass


References

Design Patterns

Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides

PHP 5

The Official PHP web site
Core PHP Programming, 3rd Edition by Leon Atkinson and Zeev Suraski
Sign In
to add the first comment for PHP Design Patterns PHP OO Class Basics.