Skip to main content

PHP Access Modifiers

An access modifier (also called a visibility keyword) decides where a property or method can be used from.

PHP offers three of them:

  • public - available from anywhere; this is the default
  • protected - available inside the class and inside classes derived from it
  • private - available ONLY inside the class that defines it

Note: Leave the modifier out and PHP treats the property or method as public.


Public Access Modifier

Marking a property or method public means any code can reach it, inside or outside the class.

In the next example, code outside the class can use both the $name property and the get_details() method.

Public Example

Code outside the class sets a public property and calls a public method:

Prompt
Write a PHP script that defines a Fruit class with a public $name property and a public get_details() method. Create a Fruit object, set its name directly, and display it.
Output: PHP script

Private Access Modifier

private is the strictest modifier: only code inside the defining class can touch the property or method.

In the next example, $name is private, so reaching for it directly from outside the class fails.

Private Example

Assigning a value to a private property from outside the class causes a fatal error:

Prompt
Write a PHP script that defines a Fruit class with a private $name property. Create a Fruit object and try to set the name property directly to show that it causes an error.
Output: PHP script

Protected Access Modifier

protected sits in between: the class itself and its derived classes (child classes) have access, but outside code does not.

In the next example, $name is protected, so direct access from outside is not allowed.

Protected Example

Assigning a value to a protected property from outside the class causes a fatal error:

Prompt
Write a PHP script that defines a Fruit class with a protected $name property. Create a Fruit object and try to set the name directly to show that it causes an error.
Output: PHP script

Protected with Inheritance

A child class is allowed to read a protected property it inherited:

Prompt
Write a PHP script that defines a Fruit class with a protected $name property and a setType() method. Then define an Apple class that extends Fruit and has a getType() method. Show that the protected property is accessible in the child class.
Output: PHP script