What is class in php


 

 

 

 

 

 

 

 

 

 

Writing a class example in php

 

A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. A class is defined using the following syntax:

<?php
class Cart {
var $items;  // Items in our shopping cart

// Add $num articles of $artnr to the cart

function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}

// Take $num articles of $artnr out of the cart

function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
} else {
return false;
}
}
}
?>

This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.

Warning

You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:

<?php
class test {
?>
<?php
function test() {
print ‘OK’;
}
}
?>