How to make a class in PHP

From version 5, PHP introduced object oriented programming, otherwise known as OOP. Because of OOP, today we can say that PHP is a fully-featured language capable of building a lot of applications.

In this shot, by mentions of OOP, we are referring to the use of classes. A class is a piece of code that identifies an abstract concept.

Inside a class, we have:

  • Variables, which are called properties.
  • Functions, which are called methods.

Let’s look at a visual representation of a class.

%0 node_1 class node_2 methods node_1->node_2 node_3 properties node_1->node_3 node_1634059035571 doSomething() node_2->node_1634059035571 node_1634059058845 doSomethingElse() node_2->node_1634059058845 node_1634059129478 $propriety node_3->node_1634059129478

Example

We can define a class with the keyword class. After writing the name of the class, we can define our methods and properties. Both can have visibility: public, private, and protected. A class needs to be initialized with the new keyword.

Let’s look at an example.

<?php
class MyHello {
private $sampleHello;
public function __construct(){
$this->sampleHello = "Hello, educative!";
}
public function sayHello(){
echo $this->sampleHello;
}
}
$instance = new MyHello(); // inizialize a class
$instance->sayHello(); // call a method

Explanation

In the code above, we have constructed a class named MyHello. The class has one private property called $sampleHello and two public properties called the __construct() (the constructor of the class) and sayHello().

In line 13, a new instance of the class is created using the new keyword. Then in line 14, the sayHello() method is invoked of the previously created instance.

Free Resources