Blog

In PHP a Brief Explanation of Private Properties and Methods in Class
Posted on June 23, 2015 in OOP, PHP by Matt Jennings

<?php

class GrandPa
{
    private $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 results in a notice (Notice: Undefined property: Daddy::$name) or nothing at all because:
- An inherited class CAN'T inherit private properties and methods of a parent class.
*/
echo $daddy->displayGrandPaName();


$objectInstanceOfGrandPa = new GrandPa();
/*
- Code below results in a fatal error because private class properties and methods:
-- ONLY have access to the class itself.

-- NOT object instances of the class itself, inherited classes, OR object instances of inherited classes.

*/
echo $objectInstanceOfGrandPa->name;

?>

Leave a Reply