Saturday, September 22, 2007

Simple PHP Class Example

/* Simple Class Structure */
class MathOperation
{
var $value1;
var $value2;

function Sum($value1, $value2)
{
$result = $value1 + $value2;
return $result;
}
function Diff($value1, $value2)
{
$result = $value1 - $value2;
return $result;
}
function Prod($value1, $value2)
{
$result = $value1 * $value2;
return $result;
}
function Quot($value1, $value2)
{
$result = $value1 / $value2;
return $result;
}
}

/*
STRUCTURE : [object variable name] = new [class name]

$compute : is the variable name of the new class object that we created
MathOperation : is the name of the class that we creayed
*/

$compute = new MathOperation;

/*
STRUCTURE : [object variable name] -> functionname(parameter1, parameter2)

$sum : is the variable which would hold the result of the class function that we called
Sum() : is the class function that we called
2 : would be assigned to $value1
9 : would be assigned to $value2
thus, "$value1 = paramater1, $value2 = parameter2" and so on
*/

$sum = $compute->Sum(2,9);
$diff = $compute->Diff(5,6);
$prod = $compute->Prod(3,2);
$quot = $compute->Quot(7,3);

/*This will display the result of the above operation*/

echo "Sum(2,9) = $sum, Diff(5,6) = $diff, Prod(3,2) = $prod, Quot(7,3) = $quot";

/*
OUTPUT :

Sum(2,9) = 11, Diff(5,6) = -1, Prod(3,2) = 6, Quot(7,3) = 2.33333333333
*/

No comments: