Object-Oriented PHP for Beginners

January 01, 2012 // In: PHP
Today, We’ll discuss about Object-Oriented PHP Programing for Beginners. So Lets start…
Object-Oriented is a style of coding. For many programmers Object-Oriented is very complex and full of complicated syntax. But realty is, Its very easy and very effective programming style.
Object-Oriented is a style of coding in which related actions or tasks are grouped together in a class. Object-Oriented Programming helps you to follow Dont’t Repeat Yourself (DRY). The major benefit of DRY is that, If a piece of information is changed, you need to change only from one place. The maintaining the code is the big issue for developer. It seems OOP is more complex than simple procedural coding. But realty is, OOP is very straightforward and simple.

Objects and Classes

Before going to deep in OOP, a basic understanding of difference between Object and Class is necessary.
Some developers use the terms class & object interchangeably. But
A class is a theory, for example , is like a blueprint of a house. It defines the shape of the house on paper, with relationships between the different parts of the house, even though the house doesn’t exist.
An object, then, is like the actual house built according to that blueprint. The data stored in the object is like the wood, wires, and concrete that compose the house: without being assembled according to the blueprint, it’s just a pile of stuff. However, when it all comes together, it becomes an organized, useful house.
Classes form the structure of data and actions and use that information to build objects. More than one object can be built from the same class at the same time, each one independent of the others. Continuing with our construction analogy, it’s similar to the way an entire subdivision can be built from the same blueprint. i.e 50 different houses that all look the same but have different families and decorations inside.
Structure of Class
The syntax to create a class is very simple. You can declare a class by using class keyword, followed by the name of the class and with two curly braces ( {} ).


class myclass
{
// Class Properties and Methods here…
}
?>

After creating a class, new class can be instantiated and stored in a variable using the new keyword.

$obj = new myclass;

and to see the contents of the class use var_dump();

var_dump($obj);

Try out this, by putting all the code in a new file.


class myclass

{
// Class Properties and Methods here…}
$obj = new myclass;
var_dump($obj);
?>

in my case the result is..

object(myclass)[1]

Defining Class Properties/Variables
To add data to a class, properties or class specific variables are used. They work like regular variable but can only be accessed through the object as they are bound only to the object.
The syntax to declare a property/variable, use the access modifier ( access specifier), followed by variable name.
public $var1 = “Its Me!”;
The keyword public means it can be accessed anywhere, there is no restriction on its accessibility. It can be access inside as well as outside the class. Private, Protected keywords can also be used.
To read this property and output it to the browser, reference the object from which to read and the property to be read.
echo $obj->var1;
Because multiple instances of a class can exist, if the individual object is not referenced, the script would be unable to determine which object to read from. The use of the arrow (->) is an OOP construct that accesses the contained properties and methods of a given object.
Modify the script and update it with the new one.


class myclass
{
public $var1 = “Its Me!”;
}
$obj = new myclass;
echo $obj->var1;
?>

Output:

Its Me!

Defining Class Methods

Methods are the functions. Individual functions or actions that an object will be able to perform are defined in the class as Method. The syntax to create methods in the class is just like regular method.
You need to write Access Modifier.
public function func_name()
{
     // Contents goes here…
}
For instance, we create two methods to get and set the values of variable/property we recently declared.

class myclass
{
         public $var1 = “Its Me!”;
         public function getValue()
        {
                return$this->var1;
        }
        public function setValue($val)
        {
                $this->var1 = $val ;
        }
}
$obj = new myclass;
echo $obj->var1;
?>
OOP allows objects to reference themselves using $this. When working within a method, use $this in the same way you would use the object name outside the class.
To use these methods, call these methods just like regular functions.

class myclass
{
         public $var1 = “Its Me!”;
         public function getValue()
        {
                return $this->var1.”
“;
        }
        public function setValue($val)
        {
                $this->var1 = $val ;
        }
}
$obj = new myclass;
echo $obj-> getValue();
$obj->setValue(‘Its New Value’);
echo $obj-> getValue();
?>
Output
Its Me!
Its New Value
You can use Multiple instances of the class.

class myclass
{
         public $var1 = “Its Me!”;
         public function getValue()
        {
                return $this->var1.”
“;
        }
        public function setValue($val)
        {
                $this->var1 = $val ;
        }
}
$obj = new myclass;
$obj2 = new myclass;
echo $obj-> getValue();
echo $obj2-> getValue();
$obj->setValue(‘Its New Value’);
$obj2->setValue(‘Its New Value’);
echo $obj-> getValue();
echo $obj2-> getValue();
?>
Output
Its Me!
Its Me!
Its New Value
Its 2nd New Value
Constructors and Destructors
When an object is instantiated, it’s often desirable to set a few things. To handle this, PHP provides the magic method __construct(), which is called automatically whenever a new object is
created. To call a function when the object is destroyed, the __destruct() magic method is available. This is useful for class cleanup (closing a database connection, for instance).
public function __construct()
{
        //contents here..
}
public function __destruct()
{
      //contents here…
}
To explicitly trigger the destructor, you can destroy the object using the
function unset()..
unset($obj);
Class Inheritance
A class can inherit the methods and properties of another class using the extends keyword. Now, create a second class that extends myclass.

 

class myclass

 

{
         public $var1 = “Its Me!”;
         public function getValue()
        {
                return $this->var1.”
“;
        }
        public function setValue($val)
        {
                $this->var1 = $val ;
        }
}
class otherclass extends myclass
{
       public function show()
        {
                return “I’m from otherclass”;
        }
}
$newobj = new otherclass;
echo $newobj->getValue();  
echo $newobj->show(); 
?>
Output
Its Me!
I’m from otherclass
Getting Started With PHP Part-1
Create a Secure Login Script in PHP (updated)