Skip to main content

PHP Object Oriented Programming (OOP)

By SamK
0
0 recommends
Category(s)
Topic(s)

Since PHP 5, you can also write PHP code in an object-oriented style.

In procedural programming, you focus on writing functions or procedures that perform operations on data, whereas in object-oriented programming, you create objects that encapsulate both data and methods (functions).

Object-oriented programming offers several advantages over procedural programming:

  • OOP can be more efficient and easier to execute
  • OOP provides a clear and organized structure for programs
  • OOP promotes the DRY (Don't Repeat Yourself) principle, making the code easier to maintain, modify, and debug
  • OOP enables the creation of fully reusable applications, resulting in reduced code and faster development times

Classes and Objects

Classes are schematics for creating objects. A class defines the properties (attributes) and methods (functions) that objects created from the class will have.

Objects are instances of classes, containing specific data and behaviors as defined by their respective class. Each object can have unique values for its properties while sharing the same structure and methods.

Example:

<?php 
// A class named Car having properties and methods
class Car {
  // Properties
  public $make;
  public $model;

  // Methods for setting and retrieving make value
  function set_make($make) {
    $this->make = $make;
  }

  function set_model($model) {
    $this->model = $model;
  }

 // Methods for setting and retrieving model value
  function get_make() {
    return $this->make;
  }

  function get_model() {
    return $this->model;
  }
}

// Defining two objects of class Car
$car1 = new Car();
$car2 = new Car();

// Setting property values using methods
$car1->set_make('Toyota');
$car1->set_model('Corolla');
$car2->set_make('Honda');
$car2->set_model('Civic');

// Retrieving property values using methods
echo $car1->get_make() . " " . $car1->get_model();
echo "<br>";
echo $car2->get_make() . " " . $car2->get_model();

/*
Output:
Toyota Corola
Honda Civic
*/
?>

Questions & Answers