What is a class in PHP?

In PHP, we can define a class by using the “class” keyword. It encapsulates the properties (attributes) and behaviours (methods).

The class is the blueprint or a set of instructions to build a specific type of object.

  1. The class is a template for objects.
  2. The class is an entity that is used to determine how an object will behave and what the object will contain.
  3. The class is used to hold the objects along with their behavior and properties.
  4. It is a programmer-defined data type, that includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.

Example1

<?php
class Car {
public function name() {
    echo " This is the Simple Example of class";
}
}
$obj= new Car;
$obj->name();
?>

Output

This is a Simple Example of a class

Example 2

<?php
class Fruit {function name($parm) {
echo $parm;
  }
}
$apple = new Fruit();
echo $apple->name("Mango");
?>

Output

Mango

Example 3

<?php
class Car{
   private $name= "My Fav Car Hyundai Creta"; 
   public function display(){
      echo $this->name; 
   } 
}
$obj = new Car();
$obj->display();
?>

Output
My Fav Car Hyundai Creta

 


Prev Next