Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Accessing protected var from child class

I'm learning PHP and I'm stuck i the following code:

<?php

class dogtag {

    protected $Words;

}

class dog {

    protected $Name;
    protected $DogTag;

    protected function bark() {
        print "Woof!\n";
    }

}

class poodle extends dog {

    public function bark() {
        print "Yip!\n";
    }

}

$poppy = new poodle;
$poppy->Name = "Poppy";
$poppy->DogTag = new dogtag;
$poppy->DogTag->Words = "My name is
Poppy. If you find me, please call 555-1234";

var_dump($poppy);

?>

This is what I got:

PHP Fatal error:  Uncaught Error: Cannot access protected property poodle::$Name

This looks strange to me as I should access protected vars and functions from child classes.

Could please someone explain where I'm wrong?

Many thanks.

like image 203
S4rg0n Avatar asked Jul 10 '26 10:07

S4rg0n


1 Answers

Protected variables can indeed be accessed from the child class. However you aren't accessing your variable from inside the child class.

If you make the variables public you can access them from outside the class.

Documentation: http://php.net/manual/en/language.oop5.visibility.php

Example:

Class Dog {

   private $privateProperty = "private"; //I can only be access from inside the Dog class
   protected $protectedProperty = "protected"; //I can be accessed from inside the dog class and all child classes
   public $publicProperty = "public"; //I can be accessed from everywhere.

}


Class Poodle extends Dog {

   public function getProtectedProperty(){
       return $this->protectedProperty; //This is ok because it's inside the Poodle (child class);
   }

}

$poodle = new Poodle;
echo $poodle->publicProperty; //This is ok because it's public
echo $poodle->getProtectedProperty(); //This is ok because it calls a public method.
like image 152
Daan Avatar answered Jul 12 '26 01:07

Daan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!