Access Specifiers: PHP OOP
Controlling Access with public, private and protected access modifiers.
These access specifiers can be used on both variables/attributes and methods.
In this video tutorial, we’ll demonstrate it using attributes.
Access Specifiers:
1. public
2. private
3. protected
Class With Attributes
var $a is similar to writing public $a
We shall extend class container to another class called contains.
Extending class is an inheritance property, and we shall discuss inheritance in another article. For now, know that, with extends keyword, all the properties and methods with public / protected access are inherited.
Extends
Here, contents of class container is extended by class contains.
Object of class container
a;
echo $obj1->b;
?>
This outputs: 10 and 20 respectively.
Object of class contains
a;
echo $obj2->b;
?>
This outputs: 10 and 20 respectively.
i.e., public attributes are inherited
Accessing private / protected attributes outside class
c;
echo $obj1->d;
?>
It through’s error, since you cannot access, private and protected variables/attributes outside the class.
Now lets check if private and protected variables are actually inherited:
Inheriting private attribute
c;
}
}
$obj1 = new contains();
?>
This through’s error, because $c is not inherited to class contains and thus not present inside class contains. Which means, private variables and methods cannot be inherited.
Inheriting protected attribute
d;
}
}
$obj1 = new contains();
?>
Output’s 40.
This means, protected variables and methods are inherited.
Access Specifiers: PHP OOP
Conclusion
public attributes and methods are inherited and can be accessed outside the class.
private attributes and methods cannot be inherited and cannot be accessed outside the class.
protected attributes and methods can be inherited but cannot be accessed outside the class.