home ~ previous

PHP

Classes

In OOP, you could look Classes being a road and an Object, a car that drives on that road.

The Class dictates where the car can go. The Object (car) then travels on it, going in any direction it chooses, stopping here and there, picking up passengers and so on, but ultimately it only goes along the roads that have been designed by the Classes.

There are many more analogies out there, so if this one doesn’t work for you, you can find another that does.

Lets look at a Class in PHP and an inherited class:

<?php

class Fruit {
	## When calling a variable in a class, you have to declare var. 
	## It is known as an attribute.
	## When declaring var, you are declaring a Public modifier (so you could replace var with Public).
	var $apples = 4;
	var $prunes = 4;

	## A function in a class is called a method. Note the $ has been dropped.
	function morefruit(){
		return $this->apples + $this->prunes;
	}
}

## The entends creates an 'inheritated' class.
## In this example, InheritedFruit inherits all of the behaviours ofthe class Fruit.
## This means that it we can share/inherit all of the behaviours from a 
## previous class, without redeclaring them.
## We can also overwrite values. 

class InheritedFruit extends Fruit {
		var $prunes = 6;
		function morefruit(){
		return $this->apples + $this->prunes + 120;
	}
}

## Here we create objects that call on the declared classes.
$obj1 = new Fruit();
$obj2 = new InheritedFruit();

## here we echo the variable declared in the class. Note that the $ has been dropped.
echo $obj1->apples . "<br />";
echo $obj1->prunes . "<br />";
echo $obj1->morefruit() . "<br />";

echo $obj2->apples . "<br />";
echo $obj2->prunes . "<br />";
echo $obj2->morefruit() . "<br />";

?>

home ~ previous

Rohan Leach .... thoughtful