This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
A class is a template for objects, and an object is an instance of class.
A class is defined by using the
keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property:
<?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } ?>
<?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit(); $banana = new Fruit(); $apple->set_name('Apple'); $banana->set_name('Banana'); echo $apple->get_name(); echo "<br>"; echo $banana->get_name(); ?>
In the example below, we add two more methods to class Fruit, for setting and getting the $color property:
<?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } function set_color($color) { $this->color = $color; } function get_color() { return $this->color; } } $apple = new Fruit(); $apple->set_name('Apple'); $apple->set_color('Red'); echo "Name: " . $apple->get_name(); echo "<br>"; echo "Color: " . $apple->get_color(); ?>
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
<?php class Fruit { public $name; function set_name($name) { $this->name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); ?>
2. Outside the class (by directly changing the property value):
<?php class Fruit { public $name; } $apple = new Fruit(); $apple->name = "Apple"; ?>
You can use the instanceof keyword to check if an object belongs to a specific class:
<!DOCTYPE html> <html> <body> <?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit(); var_dump($apple instanceof Fruit); ?> </body> </html>
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon
Module 6 quiz