PHP OOP Accessing Protected Properties

PHP OOP Accessing Protected Properties

When you are using protected properties, they can be accessed with subclasses. However, if you want to print a protected variable from its parent class after you instantiate an object, you will receive a warning message.

The easiest way to explain this is to show the following example. As you can see, if you instantiate an object in the subclass and run a protected method from its parent, you will have access to all properties in the parent class and be able to return it. The reason for this is that the subclass has access to the method of the parent class. Then, the parent class method has access to all properties. However, if the method was private, you would not be able to use the method from the child class.

Besides that, you can output a property from the parent class using echo $test->name;. But, you will not be able to print a protected or private property from the instantiated Form() object. Therefore, printing $test->name2 gives you nothing.

All in all, the usage of public, protected and private properties and methods are what make OOP PHP such a well, organized technique for writing disciplined code.

class Tag
{

    public $name = "Peter";
    protected $name2 = "Paul";
    private $namethree = "Mary";
    private $myvar = "test";

    public function fromparent()
    {
        echo "hey public";
    }

    private function fromprivateparent()
    {
        echo "hey private";
    }

    protected function fromprotectedparent()
    {
        echo "Hey protected variable called: ";
        //$this->myvar = "testin";
        return $this->myvar;
    }

}

class Form extends Tag
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->fromprotectedparent();
        return $this->myvar2;
    }


}

$test = new Form();
echo $test->myvar2 . " \n";
echo "\n";

echo $test->name. " \n";
echo $test->name2. " \n";