Classes define templates for creating objects, while objects are instances of these classes.
Classes:
A class defind using class keyword followed by the class name
<?php
class Car {
// Class definition goes here
}
?>
Objects:
An object is an instance of a class.
It is created using the new keyword.
Here's how you can create an object of the Car class.
<?php
$object = new car();
?>
In this, $object is an object of the Car class.
Example-
<?php
class Fruit {
public $name;
public $color;
public function color_name() {
return "This is a $this->color $this->name.";
}
}
// object create
$obj = new Fruit();
$obj->name = "apple";
$obj->color = "red";
echo $obj->color_name(); // Output: This is a red apple.
?>
- We define a Fruit class with properties $name and $color, and a method
color_name
(). - We create an object of the Fruit class named $
obj
. - We set the properties of the $
obj
object to "apple" and "red". - We call the
color_name
() method of the $obj
object, which returns a string describing the fruit's name and color.