A class is a template for objects, and an object is an instance of a class. Let's look at how to define them in PHP and how to access their internal data!
A class is defined using the class keyword, followed by the name of the class and a pair of curly braces {}. Inside the braces, you define its properties and methods.
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: The $this keyword refers to the current object, and is only available inside methods.
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.
Objects of a class are created using the new keyword.
<?php // Instantiate two objects $apple = new Fruit(); $banana = new Fruit();// Set the names $apple->set_name('Apple'); $banana->set_name('Banana');
// Get the names and output them echo $apple->get_name() . "\n"; echo $banana->get_name(); ?>
Which keyword is used to create an instance (object) of a class in PHP?