Topics Object-Oriented PHP Classes & Objects
intermediate 15 min read

Classes & Objects

Creating classes, properties, methods, constructors, and object instantiation.

Classes & Objects

class User {
// Properties with types
public string \$name;
private int \$age;
protected string \$email;

// Constructor (PHP 8+ promoted properties)
public function __construct(
public string \$username,
private string \$password,
) { }

// Methods
public function getName(): string {
return \$this->name;
}

// Static methods
public static function createGuest(): self {
return new self("guest", "");
}
}

// Instantiation
\$user = new User("alice", "secret");
echo \$user->username;

Visibility

  • public — accessible everywhere
  • protected — accessible in class and subclasses
  • private — accessible only in defining class

Examples

<?php
class Product {
    public function __construct(
        public string $name,
        private float $price,
    ) {}
    public function getPrice(): float {
        return $this->price;
    }
}
$p = new Product('Widget', 9.99);
echo $p->name . ': $' . $p->getPrice();

Your Notes

Sign in to take notes for this lesson.

Quiz

OOP Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.