PHP Protected Keyword Tutorial 🎯

beginner
5 min

PHP Protected Keyword Tutorial 🎯

Welcome to CodeYourCraft's in-depth PHP tutorial on the protected keyword! This lesson is designed to help both beginners and intermediates understand the concept of protected access modifier in PHP. Let's dive right in!

Understanding the protected Keyword πŸ“

In PHP, the protected keyword is an access modifier used to control the accessibility of classes, properties, and methods within the class hierarchy. Unlike public and private access modifiers, protected allows access within the defining class and any classes that inherit from it.

Properties and Methods with protected Access Modifier πŸ’‘

Here's a simple example of a class with a protected property and method:

php
class MyClass { protected $myProperty = "Protected Property"; protected function myFunction() { echo $this->myProperty; } }

In the example above, the $myProperty and myFunction() are both protected. This means they can be accessed by the MyClass itself and by any classes that inherit from MyClass.

Inheritance and Protected Access Modifier πŸ“

Let's create a child class and see how it interacts with the protected properties and methods from the parent class:

php
class ChildClass extends MyClass { public function displayMyProperty() { $this->myFunction(); } } $childObject = new ChildClass(); $childObject->displayMyProperty();

In the above example, ChildClass inherits from MyClass. Since myFunction() is protected, it can be called from within the ChildClass. When we call displayMyProperty() on an instance of ChildClass, it ultimately calls myFunction() in the parent class, and the protected property $myProperty is accessed without any issues.

Protected vs Private and Protected vs Public πŸ’‘

Here's a quick comparison of the protected, private, and public access modifiers in PHP:

  • Public: Properties and methods with the public access modifier can be accessed from anywhere, including from outside the class.
  • Private: Properties and methods with the private access modifier can only be accessed within the defining class. They are not accessible by any inherited classes.
  • Protected: Properties and methods with the protected access modifier can be accessed within the defining class and by any classes that inherit from it.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which of the following access modifiers allows access to properties and methods within the defining class and any classes that inherit from it?

Stay tuned for more advanced examples and practical applications of the protected keyword in PHP! If you have any questions or need further clarification, feel free to ask in the comments below. πŸ’¬

Happy coding, and welcome to CodeYourCraft! πŸš€πŸŒŸ