PHP Classes and Object-Oriented Programming Basics

Lesson Overview

Welcome! Today, we're exploring PHP classes, a fundamental aspect of Object-Oriented Programming (OOP) in PHP. Using practical examples, we'll delve into the essential concepts of PHP classes, including their structure, attributes, and methods.

PHP Classes Refresher

Let's kick off with a look at PHP classes. Crucial in OOP, PHP classes encapsulate related data and functions within a compact unit called an object. Think of a video game character as an instance of a class, with specific attributes (like health or strength) and methods (such as attack or defense).

A PHP class acts as a blueprint containing attributes and methods. Attributes represent data pertinent to a class instance, while methods are functions or actions that manipulate this data. Each class comes with a constructor, which is responsible for initializing class attributes.

In PHP, the $this keyword is essential for accessing the class instance's attributes and methods. When a new class instance is instantiated, $this allows the object to maintain its state and behaviors.

PHP
<?php

class GameCharacter {
    // Attributes
    public $name;
    public $health;
    public $strength;

    // Constructor
    public function __construct($name, $health, $strength) {
        $this->name = $name;
        $this->health = $health;
        $this->strength = $strength;
    }

    // Method
    public function attack($otherCharacter) {
        $otherCharacter->health -= $this->strength;
    }
}

?>

Note: we will cover constructors in the next unit of this course, but in the meantime, consider them just as methods that construct the instance of your class given certain input parameters!

Class Attributes

Attributes in PHP classes store data associated with each instance. In our GameCharacter class, name, health, and strength are such attributes. You can access a class attribute with an instance of the class, followed by an arrow (->), and the attribute name.

Attributes are initialized within the constructor. PHP uses the $this keyword to refer to the current object instance and set attribute values.

PHP
<?php

class GameCharacter {
    // Attributes
    public $name;
    public $health;
    public $strength;

    // Constructor
    public function __construct($name, $health, $strength) {
        $this->name = $name;
        $this->health = $health;
        $this->strength = $strength;
    }
}

$character = new GameCharacter("Hero", 100, 20);  // instance of the class
echo $character->name . "\n";  // prints: Hero
echo $character->health . "\n";  // prints: 100
echo $character->strength . "\n";  // prints: 20

?>

Here, the constructor initializes the class attributes with provided arguments, differentiating one class instance from another and maintaining the instance's state.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal