How to Declare a property, method or constant as protected in PHP ?


In PHP, we can declare a property, method or constant as protected by using the protected keyword before the property, method or constant name.

Here are examples of how to declare a protected property, method and constant in PHP:

  • Protected Property:
class MyClass {
    protected $myProtectedProperty = "This is a protected property";
}

$obj = new MyClass();
echo $obj->myProtectedProperty; // This will result in a Fatal Error as we cannot access a protected property from outside the class
  • Protected Method:
class MyClass {
    protected function myProtectedMethod() {
        echo "This is a protected method";
    }
}

$obj = new MyClass();
$obj->myProtectedMethod(); // This will result in a Fatal Error as we cannot access a protected method from outside the class
  • Protected Constant:
class MyClass {
    protected const MY_PROTECTED_CONSTANT = "This is a protected constant";
}

echo MyClass::MY_PROTECTED_CONSTANT; // This will result in a Fatal Error as we cannot access a protected constant from outside the class

Note: Protected properties, methods and constants can be accessed within the class and its child classes.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.