PHP protected Keyword
Example
Use protected
to prevent outside code from modifying a property:
<?php
class MyClass {
protected $number = 0;
}
class
AnotherClass {
public function add1() {
$this->number++;
}
public function getNumber() {
return $this->number;
}
}
$obj = new AnotherClass();
$obj->add1();
echo "The number is " . $obj->getNumber();
?>
Try it Yourself »
Definition and Usage
The protected
keyword is an access modifier. It marks a property or method as protected.
Protected properties and methods can only be used by the class in which the property or method was defined and any classes that derive from it. Any other code cannot use them.
Related Pages
The private
keyword
The public
keyword
Learn more about access modifiers in our PHP OOP - Access Modifiers Tutorial.
❮ PHP Keywords