I have come across classes very often and use classes distributed on phpclasses.org such as phpMailer, an excellent class for sending emails using PHP. A class allows programmers to separate code from the main systems while being able to access and define variables for access outside the class, inside the class or just within one function in the class.
In this article I will discuss the general structure of a simple class and usage of a simple “HELLO” class as an example.
A class should be defined in a common include. When coding from scratch in PHP, I always create an application_top.php file which I require at the top of every page to allow access to any classes, functions or general configuration for use within the sites pages.
A class is defined using the ‘class’ keyword much like a function. The class contents are enclosed between curly brackets like so:
< ?php class hello { public function printHello(){ echo "HELLO"; } private function printHello2(){//This function is only accessible from within this object. echo "HELLO 2"; } } $obj = new hello; $obj->printHello();//Prints HELLO (PHP5) //$obj->printHello2();//FATAL ERROR (PHP5) ?>
PHP5, introduced access specifiers. These are used using the keyword public or private before the variable or function declaration. Private functions and variables can only be used from within a class and will not interfere with functions and variables of the same name outside of the class. It is almost as if the class is a membrane and only certain information can be accessed from outside of that membrane.
Public variables and functions can be accessed site-wide so long as the class has been declared either in a common include or the file itself as below: (This code will not work on a PHP4 server. For PHP4, remove the word public)
< ?php class hello { function printHello(){ echo "HELLO"; } } $obj = new hello; $obj->printHello();//Prints HELLO (PHP4) ?>
The $obj variable creates a new object and the word hello tells PHP that that object is a class called hello. If this was a private function, then attempting to use this function from outside of the class will result in a fatal error. For example:
< ?php class hello { private function printHello2(){//This function is only accessible from within this object. echo "HELLO 2"; } } $obj = new hello $obj->printHello2();//FATAL ERROR ?>
Tags: Basics, Beginners, PHP, PHP Classes, PHP4, PHP5, PHP5 Classes




















