PHP OOP Classes and Objects
A class works like a template: it describes the structure (properties) and behavior (methods) that its objects will have. Each object is then one individual instance of that class.
Define a Class
To define a class, write the class keyword, then the class name, then a pair of curly braces ({}). Everything that belongs to the class, properties and methods alike, goes between those braces.
Imagine a class called Fruit. It could store a name and a color as properties, and offer two methods: one that sets those details and one that gets them.
Note: A property is simply a variable that lives inside a class, and a method is a function that lives inside a class.
Note: Inside a method, $this stands for the current object, giving you access to its own properties and methods.
Class Definition
The Fruit class, with its properties and methods:
<?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>";
}
}
?>
Define Objects
A class does nothing useful until you create objects from it. One class can produce as many objects (instances) as you need. All of them get the properties and methods the class defines, but each one stores its own property values.
You create an object with the new keyword.
Creating Objects
Here, the Fruit class produces two separate objects, $apple and $banana:
Output: PHP script
<?php
class Fruit {
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');
$apple->get_details();
// Create an object named $banana from the Fruit class
$banana = new Fruit();
$banana->set_details('Banana', 'Yellow');
$banana->get_details();
?>
PHP - instanceof
Need to find out whether an object belongs to a particular class? The instanceof keyword answers that question:
instanceof Example
Here, instanceof tests whether $apple belongs to the Fruit class, and var_dump() shows the answer:
Output: PHP script
<?php
class Fruit {
// Properties
public $name;
public $color;
}
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>