2D Imaging / Animation
Adobe Photoshop Adobe Flash 3D Imaging / Animation
Autodesk Maya Cinema 4D Game Development Valve Hammer (Source) Web Adobe Dreamweaver AJAX HTML / CSS PHP Programming C++ Java Python
September 06, 2010, 12:21 AM
Welcome, Guest. Please login or register.

Login with username, password and session length
News: Feel free to help us make a community!
 
   Home   Help / Rules Search Login Register  
Pages: [1]
 

Object-Oriented Programming in PHP 5


Replies: 1 Views: 453
Posted: September 17, 2009, 09:18 PM
Object-Oriented Programming in PHP 5

Preface

You may have heard this term somewhere before in your PHP development lifespan, and you may have always wondered what it has meant. Of course, you may not have seen it before in most examples, but it is definitely a much more efficient way of writing code and developing applications or websites.

So what does this 'Object-Oriented' mean? Well, let's go into a pretend situation here.

Think of it like this, and look around you. Literally, everything in your surrounding area is, no matter how you look at it, an object. All of these objects have certain properties and behaviors in how they react in a physical world. A box is a box, and won't move. But if you apply force to it, it will go in the direction you apply force to. A table can hold as many objects you want on top of it so long as the objects on top of it don't break the table. A book can open or close, and contains any amount of pages, so long as there is print to read. All these objects have properties and behaviors, like mass, height, width, and they all have physical positions. They also use certain methods as well to utilize the objects, like you can store objects inside a box once you open it up, so long as there is free space. Or flip to the next page of a book if there are still pages left.

So what's my point? Well, much like we treat physical objects in the world, we tend to treat code as if they were objects as well. Reading this tutorial, you may find that you use a hyperlink to stumble across this. And scrolling down the page requires you to use the scrollbar at the side of a certain type of browser. We treat those things that we overlook so much as objects in code, as in they have their own properties (like where does the hyperlink go to, or how much can the scrollbar go up or down). In Object-Oriented Programming, we write our code as if what we are going to make, is an object.

Some Things to Know

As much as this may confuse you, we write objects as if they were functions, but we do not call it an object - we call it a class. The class is the outline for how the object will act and what it can do. From this class, we can create ANY amount of objects we so choose.

Inside this class, we will define functions and variables to use, but there will also be modifiers to affect how they are used - called visibility modifiers. These visibility modifiers will change who, what and how the functions/variables are used. You'll see soon.

Objective

To fill your brain with the wonders of OOP! (and maybe show you the basic design behind an application/website)

Making Your First Class

So let's take a look at the following code, and see what it does.

Code:
<?php
class 
MyClass {
public function hello_world(){
print "Hello World!";
}
}

$test = new MyClass;
$test->hello_world();

?>


Okay, let's break it down.

Step 1: we defined a new class that we named 'MyClass'

Step 2: inside this class, we made a new function called 'hello_world()'

Step 3: the definition was to print out the text "Hello World!"

Step 4: near the end of the file we instantiated (created, initialized) a new object of MyClass type

Step 5: we initiated MyClass' hello_world() method

Step 6: the result is a "Hello world!" appearing on your screen

But what's the new syntax for this code? Well let's see what we basicallly used:

1. 'class', which stands for 'we are defining a new class'
2. 'public', which is a visibility modifier which I will discuss in one second
3. 'new', meaning we will create a new object of MyClass
4. '->', meaning "hey, use this object's function named 'hello_world()'!"

There are also the visibility modifiers to discuss.

The visibility modifiers are nothing more than just saying who's allowed to use what and how.

1. 'Public' basically says "hey, anyone can use this function/variable!"
1a. Meaning anything outside the class can set internal variables, which in some cases might not be good
2. 'Protected' is another term for meaning an advanced concept learned later on which you will learn
3. 'Private' means "no one outside my class can use this!"

And that's basically it for now. There are a few other key concepts used in conjunction with visibility, but you will learn those later on.

Making More Advanced Classes

So let's take a look at another example using variables and maybe more '->' pointers. This time it will feature more methods, and give you a look at more complex logic behind OOP (abbreviated Object-Oriented Programming I will use from now on).

Our second example now:

Code:
<?php

class 
MyMathHomework {

// Let's make a class to do our circular math homework
// So let's store the value Pi for circles
public $pi M_PI;

public function find_circumference($radius){
// The relationship between Pi and Circumference is
// Circumference / Diameter = Pi
// so Circumference = Diameter * Pi
// And for us, Diameter = 2 * the Radius, which is our input
// So, (2 * Radius) * pi = Circumference

$circumference = (2*$radius) * $this->pi;
print "The circumference of a circle with radius " $radius " is " $circumference "<br/>";
}

public function find_area($radius){
// The area of a circle is as follows
// Area = Pi * r^2
// or Area = Pi * (r * r)

$area $this->pi * ($radius*$radius);
print "The area of a circle with radius " $radius " is " $area "<br/>";
}

public function find_volume($radius$height){
// Now we're working with cylinders, so we're throwing in the height parameter
// Volume is nothing more than an expansion on area, so
// Volume of a cylinder = area of the circle * height

$volume = ($this->pi * ($radius*$radius)) * $height;
print "The volume of the cylinder with radius " $radius " and height "$height " is " $volume "<br/>";
}

public function find_surface_area($radius$height){
// Surface area is basically how much space is on the cylinder
// Like say if we wanted to make a label for a can, how much space can we use to make the label
// It's more or less the circumference of the circle * height

$sArea = ($this->pi * (2*$radius)) * $height;
print "The surface area of the cylinder with radius " $radius " and height " $height " is " $sArea "<br/>";
}
}

$math = new MyMathHomework;
$math->find_circumference(5);
$math->find_area(5);
$math->find_volume(54);
$math->find_surface_area(54);
?>


Basically I'm trying to use this as an example for how classes are used. All these functions return relative information regarding area, volume, and whatnot if you just pass the radius and height into the functions.

The variables are used a bit different in OOP. Since they are belonging to the class (or object per say), we use a keyword $this to call them, meaning that we are calling THIS object's property 'whatever', or in the math homework example, THIS homework's Pi variable.

Visibility modifiers affect how these variables are used and accessed as well.

After all this, we're more prepared on handling other types of OOP classes. I'll use another example using something called the Constructor.

Constructing

Let's take a look at how a constructor is used, and basically, what it does.

Code:
<?php

class 
MyConstructor1 {
// Let's test out our construction with a few examples
// We will also use a function inside a class

public function __construct($name){
print "Hello, " $name "!";
}
}

class MyConstructor2 {
// Another construction example!

public function MyConstructor2($name){
$this->print_stuff($name);
}

public function print_stuff($name){
print "Hello, "$name "!";
}
}

class MyConstructor3 {
// Our last constructor example!

public $xVar;

public function __construct($x){
$this->xVar $x;
print "Our X-Var is now " $x "!";
}
}

$c1 = new MyConstructor1("World");
$c2 = new MyConstructor2("World");
$c3 = new MyConstructor3(5);

?>


Idealy, I hope this portrayed what a constructor is, it's a very simple idea that's easily understandable.

The constructor function basically runs when an object is constructed. Anything that is defined under constructor is ran on creation/instantiation/initialization of an object. Also a constructor method can be defined by either __construct() or 'NameOfClass'().

So it's a good thing to have around, especially when you want things to start RIGHT AWAY. Or if you just feel like saving a line of code maybe.

ToString

Since we learned constructors, we should learn another fantastic method that's hidden away ready to be used, called ToString.

Code:
<?php

class 
Person {

public $name;

public function __construct($name){
$this->name $name;
}

public function __toString(){
return "Hi! My name is " $this->name "!<br/>";
}

}

$joe = new Person("Joe");
$tom = new Person("Tom");
$bob = new Person("Bob");

print 
$joe;
print 
$tom;
print 
$bob;

?>


So it sorta works like that. Think of it now, as every data type when you print them, they run like that. In classical programming languages, the String is an object made up of several characters, and the toString would be printing all those characters in the order they were assembled.

ToString basically allows us to define a set amount of text that is to be returned by the method. So if you used print in conjunction with the object, whatever ToString returned, is printed. This is useful for when you want to iterate objects which contain useful information.

Anyway, the next thing that we will go over quickly is Static.

Static!

Static, is a way of saying sort of... fixed, never moving, always there. Sort of like how objects in the physical world have a 'static' position because they won't be moved until force is applied.

It's also another way of declaring functions and variables. Static functions/variables can be used without the actual creation of a class, meaning that it's not a variable/function of an object, but rather of the class.

When designing a static function of the class, it must NOT feature any kind of $this variable inside of it, meaning it can contain no reference to anything that'd be used inside the object (variables or references to other functions).

Let's take a looksie. What if we wanted a way to count how many objects were created? We can do this by creating a static count of all the objects that are constructed.

Code:
<?php

class 
TestStatic {

public static $count;

public function __construct(){
self::$count++;
}

public static function howMany(){
print self::$count " objects have been created.";
}
}

for(
$i=0$i<10$i++){
$objects[] = new TestStatic;
}

TestStatic::howMany();

?>


Running this will tell us that 10 objects have been created. Of course, the irony in this is that we can also find out how many objects we created by counting that array we stored it in... But I digress.

The static type works in mysterious ways, never needing a direct object to use a variable/function, but rather by calling any function or variable by that of the double colon operator known as 'Scope Resolution operator', which is used primarily for calling functions and defining values.

You will have also noticed the 'self' keyword. This isn't used like it is in Python, trust me. It's simply a constant for the current class name. As you can see, caling a static property or function is used by the format 'ClassName'::property/method, meaning that we needed a class name to use that format. So to reduce our time, we can simply use 'self' as an already defined constant for what class we are currently coding in.

You will see another keyword 'parent' later on which does a similar thing ... whoops, I just spoiled the next section!

Parents and Inheritance

Parents (or inheritance), in Object-Oriented Programming, is the idea that we can have child classes of parent classes, or in another way, from a parent class, we can have as many child classes we want. And these children may differ from their parents, but will still carry over the same functions and variables from the parent.

How does this work exactly? When defining a class, we can say that we want to extend on top of a pre-existing class, or state the class is the sub-class of a parent class.

Let's apply ourselves a nice situation here. Or maybe we'll do a familiar example.

A circle (YES, back to circles) is one of the basic two-dimensional shapes in math. When moving into three-dimensional math, the circle becomes the cylidner. So the cylinder pretty much inherits all of the circle's old properties and applies new properties to it. Let's write an example about these two classes.

Code:
<?php

// You may notice I'm using a different naming style for the functions

class Circle {
public $radius;

public function __construct($radius){
$this->radius $radius;
}

public function getRadius(){
return $this->radius;
}

public function getArea(){
// Remember this? pi * (radius*radius)
// M_PI is the constant for pi, no need to keep it as a variable
return ($this->radius*$this->radius) * M_PI;
}

public function getCircumference(){
// Circumference = 2*radius * pi
return ($this->radius*2) * M_PI;
}
}

class Cylinder extends Circle {
public $height;

public function __construct($radius$height){
// When we inherit, the constructor is completely different, unless we do...
parent::__construct($radius);
// Hah! A call back to our parent's old constructor method
// We can do this when we are calling methods from our previous class
// Using $this->__construct() might not be a good idea...
// And let's set the height
$this->height $height;
}

public function getVolume(){
return $this->getArea() * $this->height;
}

public function getSurfaceArea(){
return $this->getCircumference() * $this->height;
}
}

$circle = new Circle(5);
$cyl = new Cylinder(54);

print 
"Circle area: " $circle->getArea();
print 
"Circle circumference: " $circle->getCircumference();
print 
"Cylinder volume: " $cyl->getVolume();
print 
"Cylinder surface area: " $cyl->getSurfaceArea();

?>


As you can see, functions and variables will carry over, but not everything works like it should. Using parent::__construct() is a better idea than $this->__construct(), because you are calling a method you are defining then. $this points to the class, while 'parent' points to the parent class. So if you use $this, you might just end up with a recursive calling function leading you nowhere.

Of course, we can also apply the parent::function/property tactic elsewhere, but since I weaned you into using $this, I'll stick to that.

Here's a few more stupid examples to help you understand inheritance better.

Code:
<?php

class 
Human {
...


class Joe extends Human {
Yes I am aware this isn't a good example
}

class Car {
...
}

class AwesomeCar extends Car {
You can'
t make an awesome car without regular car properties
}

class BasicComputer {
...
}

class BetterComputer extends BasicComputer {
You need all the basic computer stuff before making better computers
}

class Building {
...
}

class AnyOtherKindOfBuilding extends Building {
It is true that we need those regular building properties for any given building
}

?>


Lastly, remember the visibility mod 'protected'? Well guess where that goes.

2. 'protected' - only accessible by the class or extended classes

Basically meaning that anything defined by protected is only used by the parent class and children classes. Pretty useful for when you build classes and plan on using things for classes made later on.

So moving on, we'll hit another topic.

Class Abstraction

I showed some pretty horrific examples, all of which will be used probably better here, or maybe. I don't know. I like to keep things fresh, but I'll introduce class abstraction here.

Abstract is the idea that a class can never exist, but can be extended from. Kind of like how we can never have just a regular 'Car' or 'Building', but extensions on those ideas. In class abstraction, we define values and functions to be abstract. If a class has one abstract function or property, the class must be abstract. And we don't even need to define all methods in an abstract class. If we do not define it in the abstract class, we hint that it must be defined in the extended classes.

Let's look at my new Kitty example.

Code:
<?php

abstract class 
AbstractCat {

// We have to define this method in extended classes
abstract public function printName($name);

// Of course all kitties meow, so let's throw in a meow method
public function meow(){
return "Meow!";
}
}

class CoolCat extends AbstractCat {

public function __construct($name){
$this->printName($name);
}
public function printName($name){
print $this->meow() . " My name is " $name " the Cat!<br/>";
}
}

$tom = new CoolCat("Tommy");

?>


Now, I never actually said class abstraction is best used everywhere, but it's a good idea, and definitely up there with the Static topic under either 'cool' or 'confusing'.

The next half of the tutorial is in the following post!
« Last Edit: September 17, 2009, 09:23 PM by Steve »
Posted: September 17, 2009, 09:19 PM
Second half!

Interfaces

Alright, time for more confusing topics! Interfaces is a bit different than parents and abstraction and all that stuff, but you may or may not find a use for it. I haven't yet.

Interfaces is basically a more defined way of defining a class, except you don't even define the functions. They're an overlay for how classes SHOULD look without actually defining them. Sort of like class abstraction, but with a hint of spice (and less definition).

Code:
<?php

interface 
Device {
public function turnOn();
public function turnOff();
}

class Phone implements Device {

public function turnOn(){
print __CLASS__ " has been turned on<br/>";
}

public function turnOff(){
print __CLASS__ " has been turned off<br/>";
}
}

class Computer implements Device {
public function turnOn(){
print __CLASS__ " has been turned on<br/>";
}

public function turnOff(){
print __CLASS__ " has been turned off<br/>";
}
}

$phone = new Phone;
$comp = new Computer;
$phone->turnOn();
$comp->turnOn();
$phone->turnOff();
$comp->turnOff();

?>


It sort of works like that. And if you don't define any of the functions within the interface, you'll get A SUPER DUPER ERROR! You can also implement multiple interfaces (if you want?) and extend the interfaces as well (if you want?).

Code:
<?php

interface 
{
...
}

interface extends {
...
}

class implements A{
Why don't I just implement B if B already contains A's dataOh yeahits an example.
}

?>


More topics on the way!

And if you didn't catch it, __CLASS__ is a constant for the class name that you are in. I used it in that last example because I'm a show-off.

Constants

Well this won't be hard since we breezed through a lot of topics.

Constant basically says "I will remain the same no matter what", so it's basically something like the number PI or E or something. Something that's fixed and won't change, hence the name 'constant'.

Let's see what it does....

Code:
<?php

class 
ConstantTest {

const myConst "Hello World!";

function returnConst(){
// Oh boy, it's the hello world...
print self::myConst "<br/>";
}
}

class Another extends ConstantTest {

function again(){
print self::myConst " again?!<br/>";
}
}

$c1 = new ConstantTest;
$c1->returnConst();
$c2 = new Another;
$c2->again();

?>


So once more we see the self and parent keywords. They're not too fancy, but you can see that constants are required to use the scope resolution operator, and won't ever change. They also carry over to extended classes, as well.

Which I think now leads us to our last keyword for classes and objects....

Final

Not as in, like, 'hey, we're done'.

Final basically says 'THAT'S IT' when defining functions and classes. When you use final, you can't define that function or class again. If a class is defined as final, it means it can not have children. (Don't take that in a bad way, post-menopausal parents)

There are so many things that can go wrong with final, let's look at some of those!

Code:
<?php

class Test1 {
final public function test(){
print "I'm a final method!";
}
}

final class Test2 extends Test1 {
final public function test(){
print "error! cannot override final method test()!";
}
}

class Test3 extends Test2 {
// There's an error here too!
// Can't extend from final class!
}

?>


So if you're one of those people who write their code and want it to be set in stone forever, try out the 'final' keyword. I, for one, like to leave my objects usable for later.

Pulling It All Together

This is a lot to take in. And really, I mean A LOT. OOP is an advanced topic not suitable for the basic programmers. There's a few more key concepts out there specifically for PHP like overloading, design patterns, iteration and magic methods, but I think the topics that I covered are really necessary for already doing a lot.

The final question is - what can we do now, but I think the better question to ask is what can't we do?

Usually when I think of OOP, I think a lot about arrays, and the many derivatives it has, like queues and stacks. Those are my typically two favorite areas of working with arrays. Before we write applications, let us write better storage of arrays.

Let's make a few objects to help out our programming. These classes are helpful for a various amount of situations, no matter what you are programming.

1. A stack is like a pile. Whatever goes on top of the pile first is removed from the pile first, unless more things are stacked afterwards.
2. A queue is sort of like a waiting line. Whatever comes in first, goes out first. This is more practical for various situations.

So what we're going to have to do is define three classes - one as an array class, the other two as the stack and queue. The array class will assist us with adding things to the extended classes of stack and queue, and also help in removing objects, while the stack and queue classes will focus on handling their types of data based on methods provided by the array class.

The extra piece is the Interface that we will use. You don't have to use the interface, but I'm just making sure to keep good practice with it.
Code:
<?php
// Steven's Array
// An array-based class used to organize and manage items in an array

// We can't call our class 'Array', so I'm using something original
class sArray {

// Our array class is used to add items, get them, and remove them
// When we add items, we just append it to the array
// And when we get items, we just return them or print an error
// When removing items, we have to unset the ID, and shift all items down the array

// Let's list a few methods we will need
// - count items in the array
// - add an item to the array
// - get the array
// - remove an item from the array
// - insert item(s) into the array
// - when initializing the object, start with a previous-made array
// - shuffle the array randomly
// - reverse the list order

// Here's our list. We don't want outside sources affecting our array.
protected $myList = array();

// Let's have a single property of count so we don't have to reference other functions
public $count 0;

public function __construct($existing_list=null){
// If the array in the constructor is set, let's add the items
if($existing_list != null){
$this->addItems($existing_list);
}
}

private function updateCount($change){
// So basically just update the count by a certain number
// In most cases it's just 1 or -1
// If we wanted to, we could do something like 5 or -5
// But all methods that insert, add and remove will already update the count with this method
}

public function copy(){
// In case we are ever feeling needy and just WANT the array
$copyArray = array();

// Run a loop
for($i 0$i $this->countItems(); $i++){
$copyArray[] = $this->getItem($i);
}

return $copyArray;
}

public function countItems(){
// The regular count() method by PHP is fine
// But I want a property, so we use our own
return $this->count;
}

public function shuffle(){
// Much like the shuffle() function, but we can it ourselves
// This function loop N amount of times and replace two items chosen randomly
// N is the random number we pick that is between 1 and the amount of items
// If we have 2 items, we only really want to shuffle it one to two times
// Even if we shuffle it 50 times, the difference won't really matter
// And therefore, reduces the complexity of shuffling

if($this->countItems() != && $this->countItems != 1){
$count $this->countItems();
$howManyLoops rand(1$count);

for($i 0$i <= $howManyLoops$i++){

// Choose the random integers to use
$ran1 rand(0$count-1);
$ran2 rand(0$count-1);

// Since at least one item will get erased, let's save one for later use
$temp $this->myList[$ran1];

// Then the swaps occur here
$this->myList[$ran1] = $this->myList[$ran2];
$this->myList[$ran2] = $temp;
}
}
}

public function reverse(){
// Reverse the list so it's backwards
$reversed = array();

// Go through the array and add them to the reversed
for($i $this->countItems()-1$i >= 0$i--){
$reversed[] = $this->myList[$i];
}

// Set the class list to this reversed one.
$this->myList $reversed;
}

public function addItem($item){
// Append one item to the array
$this->myList[] = $item;
$this->count++;
}

public function add($item){
// Alias of addItem
// Just to make it brief...

$this->addItem($item);
}

public function addItems($list_of_items){
// Add items from our previous array to this array
for($i=0$i count($list_of_items); $i++){
// Add the item at position $i in $list_of_items
$this->addItem($list_of_items[$i]);
}
}

public function getItem($id){
// Make sure it's in range of our array
if($id >= && $id $this->countItems()){
return $this->myList[$id];
}else{
throw new Exception("Error: ID is not in range");
}
}

public function get($id){
// Alias of getItem()
// I like to make methods short-named, but by convention, the longer ones are proper
return $this->getItem($id);
}

public function getItems($start$stop){
// Get all items between position $start and $stop
// I suppose this can be handy for some programmed situations
}

public function insertItem($item$id){
// Insert an item into the array at position $id
// Move all items after $id one to the right to make space
if($id >= && $id <= $this->countItems()){

// Let's make sure that we have no objects in the array first
// If we don't, then we can just easily append the object
if($this->countItems() == 0){
$this->myList[] = $item;
}else{
// From the start we should count how many items exist now
$count $this->countItems();

// Let's create a copy of the array since our array during the loop will change
$copy $this->copy();
for($i $id$i $count$i++){
// Set one position above $i to the item at position $i
$this->myList[$i+1] = $copy[$i];
}

// Lastly, set $id's position to $item
$this->myList[$id] = $item;

// Increment count
$this->count++;
}
}else{
// Error message for when we're out of range with the param
throw new Exception("ID is not in range");
}
}

public function insert($item$id){
// Alias of insertItem()
// Once again, short names = helpful
$this->insertItem($item$id);
}

public function insertItems($items$id){
// Let's add an insertItems so we can append an existing array into a position
// For this, we can simply use the insertItem() method N amount of times
if($this->countItems() == 0){
// Ignore whatever position they want to insert and just set the list
$this->addItems($items);
}else{
// Make a loop to insert the new items array in the params
for($i 0$i count($items); $i++){
$this->insertItem($items[$i], $id);

// And for every new item appended, increase $id by one
$id++;
}
}
}

public function removeItem($id){
// Remove an item by ID
// If there are no items in the array, why bother?
if($this->countItems() == 0){
throw new Exception("Erorr: There are no items in the array");
}else{
// Let's hold a count of the items before we remove one
$count $this->countItems();
// Remove the item completely by unsetting
if($id >= && $id $count){

if($count == 1){
// If there was only one item to remove... just get rid of the whole thing!
unset($this->myList);
}else{
unset($this->myList[$id]);
// Making sure we don't do any unnecessary shifts
// If it was the most recent item, we shouldn't do any shifts
if($id != $count-1){
for($i $id$i $count$i++){
// Do a loop for all items above the most recently removed
// Shift them down
$this->myList[$i] = $this->myList[$i+1];
}
// and then unset the last one that was added because it can't be there
unset($this->myList[$count-1]);

// Decrement count
$this->count--;
}
}
}else{
// Just throw an exception. May as well.
throw new Exception("ID is not in range");
}

}
}

public function remove($id){
// Alias again!
// I really like simple function names because it's easier to use later
$this->removeItem($id);
}

public function removeAll(){
// This is truly a nasty function
// Unset the entire array
unset($this->myList);

// Back to zero, count!
$this->count 0;
}

public function printAll(){
// Use this to print out the list of numbers
print $this->__toString();
}

public function __toString(){
// When a print call is made, return this string

// If the list contains no items, why are we printing?
if($this->countItems() != 0){

// Run a loop through the array and append string data
for($i 0$i $this->countItems(); $i++){
$returnStr .= $i ". " $this->getItem($i) . "<br/>";
}
}
return $returnStr;
}

// End Array class
}

interface ArrayTemplate {
// All classes implementing this interface, should have the following methods
// Since we want to use different types of data structures,
// we want to implement the idea of First-in, X-out data storage.
// (X being 'first' or 'last')
// Push/pop typically add onto the array and remove the one that should get removed
// Top/bottom view whatever's on top and bottom without removal

// Methods to use in Stack, Queue, and any other class we may define in our lives
public function pop();
public function push($item);
public function top();
public function bottom();
}

class Stack extends sArray implements ArrayTemplate {

// The Stack follows a First-in, Last-out system
// It works like a stack of papers
// Pushing an item onto the pile will place it on top
// Popping the list will return the value that was most recently pushed

public function __construct($existing=null){
// If we have an array we want to use, let's set it to default
if($existing != null){
$this->addItems($existing);
}
}

public function pop(){
// Remove and return the item most recently added
// Which for this class is count() - 1
// Or the 'last ID in the array'
$id $this->countItems() - 1;
$item $this->getItem($id);
$this->removeItem($id);
return $item;
}

public function push($item){
// Add an item to the top of the stack
// Of course using methods from sArray.
$this->addItem($item);
}

public function top(){
// See what's on top of the stack without removing
// Just a quick peek we need!
// The top-most item is the one that was just recently added
return $this->getItem($this->countItems()-1);
}

public function bottom(){
// See what's at the bottom of the stack
// In this case, it's the first item that was added to the stack
return $this->getItem(0);
}

public function __toString(){
// Use toString from array class
return parent::__toString();
}
// End Stack class
}

class Queue extends sArray implements ArrayTemplate {

// The Queue follows a First-in, First-out system
// The most recently pushed item is the next in line
// The popped item is the item that is next-in-line
// Basically first come, first leaves.

public function __construct($existing=null){
// Same for the sArray and Stack - append old list if necessary
if($existing != null){
$this->addItems($existing);
}
}

public function pop(){
// Remove and return the first item in queue
// Which in this case, is the one that's in the 0th position
$item $this->getItem(0);
$this->removeItem(0);
return $item;
}

public function push($item){
// Add an item to the end of the list
$this->addItem($item);
}

public function top(){
// See who's in front
return $this->getItem(0);
}

public function bottom(){
// See who's at the end of the line
// In the Queue's case, it's the last item in the array
return $this->getItem($this->countItems()-1);
}

public function __toString(){
// Define the toString method to use in this class
// It's really just the toString from the array class
return parent::__toString();
}

// End Queue class
}
?>


So after you review three-hundred lines of Class code in PHP, you may ask yourself "What, in the WORLD, can we possibly do with this junk?"

Well hey, let's put it to good use.

Say we have a database (a pretend database, not MySQL) and we want to put in some names. Pretend they're employees or something. We want to add employee names, and the power to drop employees as we see fit. Why not do that now? Since I know some people are definitely sick of classes by now, I'll save time and we'll write a single script file to use.

And let's just say I want to fire my entire employee to be humorous.
Code:
<?php

// Basic employee names that we can start working with
$employeeNames = array("John Smith""Bob Bobberson""Tommy the Cat""Mary Jane""Clark Kent""Peter Parker");

// The database of our names
$database = new sArray($employeeNames);

// Who's still not fired?
print $database;

// Fire 'Tommy the Cat' for being a song title
$database->remove(2);

// What shall we do with our remaining employees?
print "<br/>Remaining....:<br/>" $database "<br/>";

// Let's fire them off one-by-one
$fired = new Queue($database->copy());

for(
$i=0$i $fired->count$i++){
print "Firing " $fired->pop() . " ... fired!<br/>";
}

// How many are left?
print "<br/>Employees remaining...: " $fired->count "<br/><br/>" $fired "<br/>";

// Who's next on the chopping block?
print "Next to be fired... " $fired->top() . "<br/> Last to be fired... " $fired->bottom() . "<br/>";

?>


So that's it! That's all I can basically teach you about OOP. Of course there are other things to learn about OOP like how to use static better and more practical, seeing if an instance of an object exists, and a bunch of other stuff that you can learn on your own as well. Far as I can go is giving you the basic idea of what you can do with OOP and how it can generally improve your code.

Good luck with your PHP and thanks for reading!
Pages: [1]
 
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.10 | SMF © 2006-2008, Simple Machines LLC Valid XHTML 1.0! Valid CSS!