Object oriented PHP programming: An introduction

Object oriented php programming.

By the reign of PHP 5 oops concept worked well in a server scripting language. OOPS or Object oriented programming is a very easy method of coding. If you are still not aware of OOPS concepts, just google it and collect some knowledge.

I assume you have good knowledge of OOPS concepts and you want to implement those concepts to your PHP code to make perfect output. I shall give you a small introduction to practical object oriented php coding.

An object doesn’t exist until an instance of the class has been created; the class is just a definition. When the object is physically created, space for that object is allocated in RAM. It is possible to have multiple objects created from one class. So that is something basic about classes and objects

Ok we shall move to practical implementation of classes and objects. First of all we shall make a simple class. Unlike other languages classes in php will usually be normal php files with .php extension. For convenience you can name those files as myclass.class.php. Ok now I am going to make a php class


<?php

class myclass

{

//Some code here

}

?>

Look how simple it is!

Ok now we are going to define a method or you may call functions inside this class. Well I hope you will have knowledge about methods. There is nothing special to define a method inside a class.


<?php

class myclass

{

function  myfunction()

{

echo “Hello World”;

}

}

?>

So we have a class here and a method inside this. So by creating an object of this class we can use that method. Let us see how it is to be done. For that we have to initiate the object. I am going to initiate the class in some other file, it practically good to keep your classes isolated so it can be reused by simply copying the file. Here I am going to initiate the object in mypage.php


<?php

// Include the class file first using require function

require(‘myclass.class.php’);

//Initiate the object

$main= new myclass();

?>

See $main is our object. We shall use the methods of myclass using this object. Let’s check that.


<?php

// Include the class file first using require function

require(‘myclass.class.php’);

//Initiate the object

$main= new myclass();

//Call myfuction using object

$main->myfunction();

?>

Yeah you are done. You will get the output “Hello world”. So this is your first practical step to OO php programming, expand your knowledge make great classes and share them. You will get a great collection of classes at phpclasses.org. Happy coding

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Graphic Design Blogs - BlogCatalog Blog Directory