PHP Access Modifiers 🎯

beginner
24 min

PHP Access Modifiers 🎯

Welcome back to CodeYourCraft! Today, we're diving into the world of PHP Access Modifiers. These are special keywords in PHP that help control the visibility and accessibility of classes, functions, and variables. Let's get started!

What are Access Modifiers? πŸ“

Access Modifiers are used to define the accessibility level of the class members (variables, functions, and constants). They help to protect the code from unintended access and maintain the integrity of the code.

In PHP, we have four access modifiers:

  1. Public
  2. Protected
  3. Private
  4. Default (or internal)

Public Access Modifier πŸ’‘

Public access modifier is the most common and least restrictive access modifier. When a member is declared as public, it can be accessed from anywhere within the script or from other scripts if they are included or require the script.

php
// Example of public variable class MyClass { public $myPublicVar = "I am a public variable."; } $myObj = new MyClass(); echo $myObj->myPublicVar; // Output: I am a public variable.

Protected Access Modifier πŸ’‘

Protected access modifier is a bit more restrictive than public. Protected members can be accessed within the class where they are declared and within the child classes.

php
// Example of protected variable class MyParentClass { protected $myProtectedVar = "I am a protected variable."; } class MyChildClass extends MyParentClass { function displayProtected() { echo $this->myProtectedVar; // Output: I am a protected variable. } } $myChildObj = new MyChildClass(); $myChildObj->displayProtected();

Private Access Modifier πŸ’‘

Private access modifier is the most restrictive of all. Private members can only be accessed within the class where they are declared. They cannot be accessed by child classes or from outside the class.

php
// Example of private variable class MyClass { private $myPrivateVar = "I am a private variable."; function displayPrivate() { echo $this->myPrivateVar; // Output: I am a private variable. } } $myObj = new MyClass(); echo $myObj->myPrivateVar; // Error: Undefined property: MyClass::$myPrivateVar

Default Access Modifier (Internal) πŸ’‘

If no access modifier is specified for a class member, it is assumed to be of internal accessibility, which means it can be accessed within the same script file but not from outside the file.

php
// Example of internal (default) variable function myFunction() { $myInternalVar = "I am an internal variable."; echo $myInternalVar; // Output: I am an internal variable. } myFunction();

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What is the least restrictive access modifier in PHP?


Stay tuned for our next lesson where we will explore PHP classes and objects! Remember, practice makes perfect. Keep coding! πŸ’»πŸ’ΌπŸš€