Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 9 / 68

Classes (Object-Oriented Programming)

In this lesson you will learn the basics of object-oriented programming with PHP's class syntax, so you can group data that shares the same characteristics. This is for anyone searching for "PHP class how to use".

PHP defines classes with class too. __construct is the special method used for initialisation, and -> reaches properties and methods. Think of it as an "animal blueprint" from which you can create as many concrete instances such as a dog or a cat as you like.

The sample code gives the Animal class the properties $name and $sound, and builds a message in the speak() method. Notice how the instance created with new Animal("Dog", "Woof") has its method called through ->.

A common stumbling block for beginners is $this. To reach the object's own property from inside the class you have to write $this->name; writing plain $name will not refer to it correctly. That difference tends to trip people up at first.

This mechanism is used extensively inside CMS platforms such as WordPress. PHP 8 and later also added constructor promotion, an even more concise way to declare properties.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)