Object Oriented Programming in PHP for Beginners

In this tutorial we will learn basic of object-oriented programming in PHP and how to write simple object oriented PHP code. Many programmers think that OOP coding is difficult to understand and write. After reading this tutorial it will be easy for you to prefer OOPS in PHP instead of using procedural approach. You will get define each terms in Simple word like class, object, methods, properties and more.

So let us see tutorial in more details.

What is Object-Oriented Programming?

This is just an approach of programming in which we store all functions and variables into own created custom class and access all method (functions) when require by creating its object.

Object Oriented Programming in PHP for Beginners

ex: To setup a Living room need to setup all required material for it.

Wall, Window, door, bed, fan, sofa etc..

Now wrapping all parts into a single object know as “living room”. Now all its materials are hidden and only think about Living room (object).

Why use object-oriented programming?

Usage of this programming approach depends upon programmer’s preferences. OOP offers advantages of using it which are mentioned below.

  • Easy to write reusable code.
  • Makes your life easier about programming.
  • OOPS is mainly targeted for larger applications.

Object Oriented Concepts

Class:  In OOP everything depends on class.  Class is an object’s type.

Object:  Object is the instance of class.

Eg:

String is what? – A type of variable.

So first of all we have to create type before creating an object of that type.

Methods:  functions used in object oriented programming are termed as methods or member function.

Properties:  Variables defined inside class are termed as properties or member variables.

Creating Class in PHP

Class is created with use of class keyword. In PHP classes name start with capital letters.

<?php
class Math
{
/*Properties or Member Variables*/
var $sum;

/* Methods or Member Functions*/
function add($a,$b)
{
$this->sum = $a + $b;
}
function display()
{
echo $this->sum;
}
}
?>

Creating Object in PHP

Object of class is created using “new” operator.

<?php
class Math
{
/*Properties or Member Variables*/
var $sum;

/* Methods or Member Functions*/
function add($a,$b)
{
$this->sum = $a + $b;
}

function display()
{
echo $this->sum;
}
}
/* creating object */
$obj = new Math;

?>

Calling Methods in PHP

After creating an object call methods related to that object.

<?php
class Math
{
/*Properties or Member Variables*/
var $sum;

/* Methods or Member Functions*/
function add($a,$b)
{
$this->sum = $a + $b;
}
function display()
{
echo $this->sum;
}

}
/* creating object */
$obj = new Math;

/* calling methods ralated to object */
$obj->add(5,7);
$obj->display(); 
?>

Output is: 12

How is it easy to learn object oriented programming in PHP. That’s it. 🙂

Leave a Comment