PHP Classes/Objects

PHP Classes and Objects

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!


Defining a Class

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.


Creating Objects

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.

Object Instantiation Example

<?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(); ?>


Exercise

?

Which keyword is used to create an instance (object) of a class in PHP?