HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Access Modifiers

Access modifiers are keywords that define the **visibility** of class properties and methods. They control where a specific property or method can be accessed from, which is a core part of a concept called **Encapsulation**.


The Three Access Modifiers

PHP provides three main keywords to control access:

Modifier Description
public The property or method can be accessed from anywhere (default).
protected Can only be accessed within the class itself and by derived (child) classes.
private Can only be accessed within the class itself.

1. The public Modifier

Properties and methods declared as public are accessible from outside the class. If you don't specify a modifier, PHP treats them as public by default.

<?php
    class Fruit {
        public $name; // Public property
    }

    $apple = new Fruit();
    $apple->name = "Apple"; // OK: can be accessed from outside
?>

2. The protected Modifier

The protected modifier restricts access to the class itself and any class that **inherits** (extends) it. You cannot access it from outside these classes.

<?php
    class Fruit {
        protected $name;
    }

    $apple = new Fruit();
    $apple->name = "Apple"; // Error: Cannot access protected property
?>
Tip: Use protected when you want to allow child classes to use a property while keeping it hidden from the rest of the application.

3. The private Modifier

The private modifier is the most restrictive. A private property or method can only be accessed within the specific class where it is defined. Not even child classes can access it.

<?php
    class Fruit {
        private $name;
    }

    $apple = new Fruit();
    $apple->name = "Apple"; // Error: Cannot access private property
?>
Why use Private? It prevents accidental modification of sensitive data and allows you to change the internal logic of a class without affecting other parts of your code.

Summary Comparison

Access From Public Protected Private
Same Class Yes Yes Yes
Child Class Yes Yes No
Outside Class Yes No No
Good Practice: A common pattern is to make properties private or protected and provide public methods (getters and setters) to interact with them.

What's Next?

Now that you know how to control access, let's explore how one class can inherit properties and methods from another in the **PHP Inheritance** lesson.