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!
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:
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.
// 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 is a bit more restrictive than public. Protected members can be accessed within the class where they are declared and within the child classes.
// 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 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.
// 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::$myPrivateVarIf 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.
// Example of internal (default) variable
function myFunction() {
$myInternalVar = "I am an internal variable.";
echo $myInternalVar; // Output: I am an internal variable.
}
myFunction();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! π»πΌπ