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.
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.
<?phpclass 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.