In this tutorial we are going to learn the object oriented programming concepts in PHP. One way of programming is procedural programming, but OOPs is more easy and user friendly. It’s an idea of looking at certain things in a program as objects. You can consider object as a real time entity. These objects have properties (characteristics) and methods (functions). Every object has a class.
Class is nothing but a unit which encloses an objects properties and methods together at one place.
So let us work on Object Oriented Programming in this PHP OOPs tutorial.

Follow the steps.

  1. Create a new folder in htdocs folder in the xampp folder located in C drive and name it as OOPs.
  2. Open a new notepad++ document and save it as index.php in the newly created folder OOPs located in the htdocs folder.
  3. Now again create a new folder named CLASSES in the folder OOPs. This folder is to store the PHP files in which separate classes are written. Actually there is no compulsion to create a separate folder for classes, but it’s a good practice to have your classes together in one folder.
  4. Your OOPs folder now contains the following things:
  5. OOPs_folder
    fig 1

  6. Now open a new notepad++ file and save it as car.php in the folder CLASSES created inside OOPs folder. We are going to write a class for car and it will be best understood as car is a real time entity/object.
  7. Write the following HTML code in index.php file:
  8. <!DOCTYPE html>
    <title>PHP OOPs</title>
  9. Now write the following code to create a class in car.php file:
  10. <?php
    class Car         
     public $make;  // properties of Car class
     public $model;
     public $color;
    • We see a class Car defined in the above code.
    • A class gathers all its properties and methods/functions together at one place.
    • A class is defined with a keyword class and then its name, in this case Car. It is a naming convention that the name of a class should have a capital initial letter.
    • A class has an opening and closing curly braces that encloses its properties and methods.
    • We have declared variables for properties of car viz. $make, $model and $color.
    • We can assign the values for make, model and color in these variables.
    • Next thing we see is the access specifier given to the properties i.e. public.
    • An access specifier allows or restricts a value to be accessed.
    • We have 3 access specifiers, public, private and protected.
    • A public access specifier allows a value to be accessed anywhere in a project.
    • A private access specifier allows a value to be accessed within a class where it is declared and not outside it.
    • A protected access specifier allows a value to be accessed within a class as well as in another class that have extended the class.
    • In the above example the properties of Car class will be accessed anywhere in the project.
  11. We now want to access or use the Car properties, so write the following code in index.php.
  12.  <?php include 'CLASSES/car.php';?>
     <!DOCTYPE html>
     <title>PHP OOPs</title>
       //creating variables of car class
       $car1=new Car(); 
       //assigning values to properties of Car class
       echo $car1->make;
    • In the above code, we have seen the HTML part earlier.
    • In this index.php file we have now included or linked the car.php file through the statement written above the DOCTYPE statement shown below:
    • <?php include 'CLASSES/car.php';?>
    • The include keyword does the work of linking the two files so that we can access the properties and methods of class Car.
    • Next, the code in the body section creates an object of class Car and assigns value to its property as shown below:
    • <body>
        //creating variables of car class
        $car1=new Car(); 
        //assigning values to properties of Car class
        echo $car1->make;
    • Here, the statements with 2 slashes (//) are the comments.
    • The statement $car1=new Car(); forms an object.
    • In this $car1 is a simple variable, but when it is assigned with new Car(); it gets a memory for all the property members defined in the class Car and it becomes an object.
    • And we need to remember that all the class properties and methods can be accessed using its object.
    • So now we can assign or access values to and from the class members.
    • In the above code we have assigned a value Toyota to the property make of class Car using a statement $car1->make=”Toyota”;.
    • The value is assigned or retrieved using an arrow operator (->).
    • This value will be stored in the $car1 object.
    • The statement echo $car1->make;
      displays the value on the browser.
    • The output is shown below:
    • make_property_output_for_$car1_object
      fig 2

  13. Now, let us add a method to class Car. Write the following code in car.php file:
  14. <?php
    class Car         
     public $make;  // properties of Car class
     public $model;
     public $color;
     public function start()
    	echo 'Car Starting......';
    • In the above code, we have just newly added a method/function named start() having a public access specifier.
    • This function just displays statement “Car Starting…… “.
  15. Now to access this start() method in the index.php file, we need to write the following code:
    • First of all comment the following code:
    • $car1->make="Toyota";
      echo $car1->make;
    • Then write the following code below the statement after the object is created.
    • $car1->start();
    • Here we have called the start() method using $car1 object.
    • The output is shown below:
    • srart_method_output
      fig 3

  16. Now, let us demonstrate the private access specifier.
    • Make all the properties in class Car private. i.e. replace public with private and save the changes.
  17. Now try to assign a value to the property make as shown below:
  18. $car1->make="Toyota";
    • This will give you an error because now the property make is no longer accessible in index.php file due to private access specifier.
    • The error is shown below:
    • error_in_accessing_due_to_private_access
      fig 4

    • It is always good to have a private access specifier for the members of a class so that an important data cannot be accessed by anybody else.
    • But then how to access the properties and methods if required?
    • Solution for it is to write some public methods in the class itself which will give an access to the private members.
  19. Let us write a public method setMake() which will allow the user to assign a value to the make property of Car class. So write the following setMake() method below the start() method in car.php file:
  20. public function setMake($make)
    • Here, we have declared a public parameterized function setMake() to assign a value to make property of class Car.
    • Statement inside the function, $this->make=$make; assigns a value in variable $make to the make property of the class.
    • $this denotes the actual variable i.e. the variable declared in the class for make.
  21. This function is called from index.php file in the following way:
  22. $car1->setMake('Ford');
  23. The method setMake() only assigned the value to make property. So to access it we need to write another method say getMake() to retrieve the value. Write the following public function getMake() in car.php file:
  24. public function getMake()
    	return $this->make;
    • This function does not take any parameter, because it has to return a value not set a value.
    • The statement return $this->make; returns the value of make property.
  25. This function is called from index.php in the following way:
  26. echo $car1->getMake();
  27. The output is shown below:
  28. assign_&_access_values_through_public_methods
    fig 5

  29. Now let us learn about Constructor.
    • Constructor is a method or a function in a class that is invoked when an object is created.
    • Constructor is always the first function of a class written after the properties are declared.
    • Syntax of constructor is:
    • function __construct()
    • Here, function and construct are the keywords and they have first a space and then two underscores in between them.
    • Constructor is used to instantiate an object.
    • So let us create a constructor for the Car class in car.php file. Write the following code in car.php file below the properties:
    • public function __construct()
      	echo 'Car Created...';
    • When called the constructor in this case will display “Car Created…”.
    • Now let us call the constructor in the index.php file. The code in shown below:
    • $car1=new Car();
    • You can see here, instead of calling constructor we have just written the code of creating an object of car.
    • There is no need of being surprised, because we call the constructor of any class with the class name.
    • So in the above statement Car() is the constructor.
    • Here we know that new keyword will provide memory to the object and the Car() will call the constructor and provide initial values if any.
    • Hence as soon as object is created the constructor gets executed immediately.
    • If constructor is not written in any class, a default constructor is called.
    • So now as soon as the object $car1 is created you will see the following output:
    • parameterless_constructor_output
      fig 6

    • We can also add parameters to a constructor i.e. we can have a parameterized constructor.
    • Just add parameters to our constructor of Car class as shown in the following code:
    • public function __construct($make,$model,$color)
      	//echo 'Car Created...';
    • Here we have passed $make, $model and $color parameters to the constructor.
    • This constructor will set the values for make, model and color properties passed by the user using the statements $this->make=$make;, $this->make=$model; and $this->make=$color;
    • So in the index.php file the constructor with parameters will look like this:
    • $car1=new Car('Honda','Accord','Red');
    • The value Honda, Accord and Red will be set to make, model and color properties respectively.
    • Remember that in PHP we can have only one constructor, no multiple constructors are allowed.
    • But using constructor we have set the values, so now to retrieve the values we can write public methods.
    • So let us write the following code to retrieve the color of the car in car.php file:
    • public function getColor()
      	return $this->color;
    • This function will return the color of the car.
    • If we call this function in index.php file, we will get the color of the car. So write the following code in index.php file:
    • echo $car1->getColor();
    • The output is shown below:
    • getColor_output
      fig 7

  30. You can have as many objects you want.
    • Let us create another object. Write the following code in index.php file:
    • $car2=new Car('Honda','Civic','Blue');
      echo $car2->getColor();
    • This will create an object $car2 with the values assigned to the properties through the constructor.
    • And the color is retrieved by getColor() method through the object $car2.
    • Remember that every object has a separate memory in which it stores its separate values.
    • Let us see the output:
    • $car2_object_output
      fig 8

    • Here, we got the color Blue that was passed through the constructor of $car2 object.

Here we studied various OOPs concepts like creating an object, accessing properties and methods through an object, constructor and setting values through it etc. OOPs concepts are very useful because it provides us with a very nice feature i.e. Reusability.

Thus we completed our PHP OOPs concepts.


Please enter your comment!
Please enter your name here