SyntaxStudy
Sign Up
PHP Beginner 1 min read

PHP OOP Basics

PHP OOP Basics

Object-Oriented Programming organises code into classes (blueprints) and objects (instances).

Key Concepts

  • Class — template/blueprint
  • Object — instance of a class
  • Properties — data
  • Methods — functions
  • Constructor__construct()

Visibility

  • public — accessible anywhere
  • protected — accessible in class and subclasses
  • private — accessible only in the class itself
Example
<?php
class User {
    private string $name;
    private string $email;

    public function __construct(string $name, string $email) {
        $this->name  = $name;
        $this->email = $email;
    }

    public function getName(): string { return $this->name; }
    public function getEmail(): string { return $this->email; }

    public function greet(): string {
        return "Hello, I am {$this->name}!";
    }
}

$user = new User("Alice", "alice@example.com");
echo $user->getName();   // Alice
echo $user->greet();     // Hello, I am Alice!
?>