PHP Design Patterns .

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; } }
To download source right-click here and "Save As...".


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;
To download source right-click here and "Save As...".


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
Comments
Sign in to be the first to comment on PHP Design Patterns PHP OO Class Basics.