PHP code of Object Oriented Programing, Classes and Objects in PHP

Concept of using classes is very easy and the handy one. As it addresses lots of issues, you can define classes for different modules in site.

E.G. In an online community forum you may have two classes "manageThreads" class which will be responsible for all functions like insertion/creation of thread, replies to thread and show threads and other one "manageUsers" class which will contain all functions related to the users' management.

One big advantage of using Object Orientation is re-usability of code and this is equally valid in PHP web programming. If we consider above example of manageThreads class we can simply include class file on any page, define its object and use any of its function on that page, have not to recode any of funtion or stuff for different pages.


Now lets move to code details how Classes and objects work in PHP.

The Class File Defination:-
You Can name a class file some thing like manageThreads.class.php, the class word in between will help us differentiating it from normal pages.

The code in Class file (A class):-

class manageUsers()
{
function createUser($userName, $password)
{
$query="insert into users SET userName='".$userName."', password='".$password."'";
$mysql_query($query) or die(mysql_error());
}

function deleteUser($userID)
{
// Body of function here
}

}
?>

Usage of a PHP class in a page or php file:-


//mysql connection details here
//Inclusion of class file:-
include "classes/managerUsers.class.php"; //If class is in folder classes
//Defination of class object:-
$aManageUsers=new manageUsers();
//Call of a class function with class object
$aManageClass->createUser($userName,$password);//assuming $username and $password are set above in this files

?>

Now this one object $aManageClass can be used with all functions of manageUsers class in usage file. Similarly many classes can be included in a file and their objects can be defined to use their functions.

Hope it helps, give feedback as comments.

Posted in |