Blog
In PHP a Brief Explanation of Protected Properties and Methods in Class
Posted on June 23, 2015 in OOP, PHP by Matt Jennings
<?php
class GrandPa
{
protected $name = 'Mark Henry';
}
class Daddy extends GrandPa
{
function displayGrandPaName()
{
return $this->name;
}
}
// Instance of the "Daddy" subclass of the "GrandPa" parent class
$daddy = new Daddy();
// Code below echos "Mark Henry":
echo $daddy->displayGrandPaName();
$objectInstanceOfGrandPa = new GrandPa();
/*
Code below results in a fatal error because
protected class properties and methods ONLY have access to:
- The same class that inherited it.
- Subclasses that inherited the above class, which in this case is "GrandPa".
- Object instances of a subclass of the parent class, which in this case is "$daddy" listed above.
Protected class properties and methods do NOT have access to:
- Object instances of the declared class itself, which in this case is "$objectInstanceOfGrandPa" as show below.
*/
echo $objectInstanceOfGrandPa->name;
?>
Leave a Reply