PHP OOP - Classes and Objects
PHP OOP Classes and Objects
A class is a template for objects, and it defines the structure (properties) and behavior (methods) of an object.
An object is an individual instance of a class.
Define a Class
A class is defined with the
class
keyword, followed by the name of the class and a pair of curly braces ({}). All
its properties and methods go inside the braces.
Assume we create a class named Fruit. The Fruit class can have properties like name and color. In addition, the Fruit class has two methods for setting and getting the details:
<?php
class Fruit {
// Properties
public
$name;
public $color;
// Method to set the
properties
function
set_details($name, $color) {
$this->name = $name;
$this->color = $color;
}
// Method to display the
properties
function get_details() {
echo "Name: " . $this->name . ". Color: " . $this->color .".<br>";
}
}
?>
Note: Properties are variables within in a class and methods are functions within a class.
Note: The
this keyword is used within a method to
refer to the current object's properties and methods.
Define Objects
Classes are nothing without objects! We can create multiple objects (instances) from a class. Each object inherits all the properties and methods defined in the class, but each object will have their own property values.
Objects
of a class are created with the
new keyword.
In the example below, we create two objects ($apple and $banana) from the Fruit class:
Example
<?php
public
$name;
public $color;
function
set_details($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_details() {
echo "Name: " . $this->name . ". Color: " . $this->color .".<br>";
}
}
// Create an object named $apple from the Fruit class
$apple = new Fruit();
$apple->set_details('Apple', 'Red');
// Set property values
$apple->get_details(); // Get output
// Create an object named
$banana from the Fruit class
$banana = new Fruit();
$banana->set_details('Banana', 'Yellow'); // Set property values
$banana->get_details();
// Get output
?>
Try it Yourself »
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class: