Thuta Learning
AdvancedProgrammingbeginner

PHP Classes and Objects

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Declare a class
  • Create an object
  • Use constructors and visibility

Let's keep it simple

A class is a blueprint that bundles together data and behavior. Property visibility is controlled with public/private/protected, and the constructor accepts the initial state an object needs.

php
<?php
class Course
{
    public function __construct(
        private string $title,
        private int $lessons
    ) {}

    public function summary(): string
    {
        return "$this->title$this->lessons lessons";
    }
}

$course = new Course('PHP', 30);
echo $course->summary();
You should see
PHP — 30 lessons

Try it yourself

Build a BankAccount class with name and balance, and make its deposit() method accept only positive amounts.

PHP Classes and Objects — The BasicsPHP

Easy traps

  • Reading a private property directly from outside the class
  • Using :: instead of -> when calling an object method

Exercise

Build a BankAccount class with name and balance, and make its deposit() method accept only positive amounts.

You'll know it worked when: PHP — 30 lessons

PHP Classes and Objects | Thuta Learning