Beginning Object Oriented Programming in PHP - Classes
(Page 3 of 6 )
A class is technically defined as a representation of an abstract data type. In laymen's terms a class is a blueprint from which new will construct our box. It's made up of variables and functions that allow our box to be self-aware. With the blueprint, new can build our box exactly to our specifications.
<?php class Box { var $contents;
function Box($contents) { $this->contents = $contents; }
function get_whats_inside() { return $this->contents; } }
$mybox = new Box("Jack"); echo $mybox->get_whats_inside(); ?>
A closer look at our blueprint shows it contains the variable $contents which is used to remember the contents of the box. It also contains two functions: Box and get_whats_inside.
When the box springs into existence, PHP will look for and execute the function with the same name as the class. That's why our first function has the same name as the class itself. The whole purpose of the Box function is to initialize the contents of the box.
The special variable $this is used to tell Box that contents is a variable that belongs to the whole class and not the function itself. The $contents variable only exists within the scope of the function Box. $this->contents is a variable which was defined as part of the overall class.
The function get_whats_inside returns the value stored in the class' contents variable, $this->contents.
When the entire script is executed the class Box is defined, new constructs a box and passes "Jack" to it's startup function. The initialization function, which has the same name as the class itself, accepts the value passed to it and stores it within the class's variable so that it's accessible to functions throughout the entire class.