PHP Tutorial Tutorials - PHP OOP Object-oriented programming

PHP OOP

Object-oriented programming (OOP) is a design philosophy. It's a programming language model based on the concept of "objects".

Let’s say we’re calculating the area of a square shape.

<?php
    function calcArea($length){
        return $length*$length;
    }
    $length = 10;
    $squareArea = calcArea($length);
    echo "The area of the square is ".$squareArea;
?>

If we also want to calculate the area of a circle. We have to define the function with another different name.

<?php
    function calcArea($length){
        return $length*$length;
    }
    $length = 10;
    $squareArea = calcArea($length);
    echo "The area of the square is ".$squareArea;
    
    function calcCircleArea($R){
        $PI = 3.1415;
        return $PI*$R*$R;
    }
    $length = 10;
    $circleArea = calcCircleArea($length);
    echo "The area of the circle is ".$circleArea;
?>

With OOP, we can bundle the data and functions within the object.The function name can be same bacause they belong to different object.This prevents the need for any shared or global data with OOP.

This is a core difference between the object oriented and procedural approaches.

The four principles(features) of OOP are:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism
Date:2019-10-08 21:21:21 From:www.Lautturi.com author:Lautturi