PHP OOP- Class and Object

A class is an independent set of variables and functions that interact to complete one or more tasks. Basically class is a template for multiple objects.

While individual instances of a class are called objects.

Class and Object

Class Object
A class is an independent set of variables and functions that interact to complete one or more tasks.Individual instances of a class are called objects.
A logical entity is a class.A physical entity is referred to as an object.
The class keyword is used to declare a class. e.g class person{}Objects are generally formed using the new keyword, such as person p1=new person().
Class is declared only once.As required, the object is generated several times.
When a class is formed, it does not allocate memory.When an object is created, it allocates memory.

For Example: Let’s suppose we have a Car class. A car class can have characteristics such as name, colour, model and so on. $name, $colour, and $model are variables that can be used to store the values of these characteristics.

When the individual objects (Honda, Toyota, etc.) are formed, they inherit all of the class’s attributes and behaviours, but the values for the properties will be different for each object.

Define a Class

The class keyword is used to define a class, which is then followed by the class name and a pair of curly brackets {}. All of its properties and methods are contained within the brackets:

Syntax:

<?php
class Car {
  // code
}
?>

 We’ll create a Car class with two properties ($name and $colour) and two methods setname() and getname() for setting and retrieving the variable $name property:

<?php
class Car {
  
  public $name;
  public $color;

  
  function setname($name) {
    $this->name = $name;
  }
  function getname() {
    return $this->name;
  }
}
?>

As we have not used echo so it will not show any output.

Define an Object

Without objects, classes are nothing! A class can be used to make many objects. Each object contains all of the properties and methods declared in the class, but the property values will be different.

Objects are generally defined using the new keyword, such as car c1=new car().

In the example below, $Toyota and $Honda are instances of the class Car:

<?php
class Car {
  public $name;
  public $color;

  function setname($name) {
    $this->name = $name;
  }
  function getname() {
    return $this->name;
  }
}

$toyota= new Car();
$honda = new Car();
$toyota->setname('toyota');
$honda->set_name('honda');

echo $toyota->get_name();
echo "<br>";
echo $honda->get_name();
?>