PHP Programmer Tutorial for Building an OOP Class.
A class is a representation of an abstract data type. What this means to the PHP Programmer is that a class is a schematic for building or constructing our box. It consists of variables and functions that allow that fictional click. With this schematic, we can construct our box exactly how we want.
class Box
{
var $stuff;function Box($stuff) {
$this->contents = $stuff;
}function click_box() {
return $this->contents;
}
}$aBox = new Box(”Alex”);
echo $aBox->click_box();
If we look at our schematic, it has a variable $stuff which is used to remember what is in the box. It also has two functions: Box and click_box.
When we “click” the box, PHP will look for and execute the function with the same name as the class. This is all that the function does, initialize the content of the box when clicked.
The variable $this is used for telling the Box that contents is a variable that belongs to the whole class and not the function. The $stuff variable will only exist inside the scope of the function Box. $this->contents is a variable that was defined to be part of the entire class.
The function click_box will return the value stored within the class’ contents variable, $this->contents.
When the PHP Programmer executes the entire script, the class Box is defined, new constructs or builds the box and passes Alex to its function. This function, which has the same name as the class, will accept the value passed to it and it will also store it within the class variable. This way it will be accessible to all of the functions throughout the class.