PHP Oops Concept - PHP OOP Classes and Objects



PHP Oops Concept

  • Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data, in the form of fields, and code, in the form of procedures.
  • A feature of objects is that an object's procedures can access and modify the data fields of the object with which they are associated.
  • COOP in PHP is a programming technique that revolves around the idea of objects and classes.
  • This technique allows for the creation of complex applications that are both easier to develop and maintain.

PHP Classes and Objects

  • Classes and objects are key concepts in object-oriented programming (OOP).

Class

  • A class is an extensible program-code-template for creating objects, providing initial values for state (member variables or attributes) and implementations of behavior (member functions or methods).
  • In OOP, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes) and implementations of behavior (member functions or methods).

Objects

  • An object is an instance of a class.
  • It's a concrete entity based on the class - an actual component in an application, with its own state and behavior.
  • In other words, an object is an entity that has state and behavior.
  • An object is an instance of a class, which is an abstract template of a thing or concept.
php-oops

Defining a Class

  • A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}).

Syntax

<?php
class car {
  // you have to write code here...
}
?>

Sample Code

<?php
class Car {
  // Properties
  public $name;
  public $brand;
  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
?>

Define Objects

  • Objects of a class are created using the new keyword.
php-oops

Sample Code

<?php
class Car {
  // Properties
  public $name;
  public $brand;
  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
$audi = new Car();
$bmw = new Car();
$ audi ->set_name('Audi');
$ bmw ->set_name('BMW');
echo $audi->get_name();
echo "<br>";
echo $bmw->get_name();
?>

Output

Audi
BMW

Related Searches to PHP Oops Concept - PHP OOP Classes and Objects