0

I am a beginner in Object Oriented Programming. I am confused with a variable being declared as PRIVATE.

 <?php class dog { private $Name; } class poodle extends dog { public function test($test){ $this->Name = $test; } } $poppy = new poodle; $poppy->test("test"); echo $poppy->Name; ?> 

As I've read, "Private variables can only be accessed by the exact class that owns them - child classes cannot access private parent functions variables"

My question is if $Name is a private property, why was the output of the script returned "test" ? Shouldn't it have output an error message since another class is trying to access a private property?

1 Answer 1

1

The answer is pretty straight forward. If you do a var_dump output on the $poppy object, you will notice why it will output test anyhow.

object(poodle)[1] private 'Name' (dog) => null public 'Name' => string 'test' (length=4) 

PHP is a dynamically typed based language, which can allocate variables in runtime without the need to declare space first. Because the property $Name doesn't exist in the object poodle (in class dog you declared it private making it not available for inheritance), it creates (declares) one on the fly (by default, non-existing variables become public).

This gives the illusion as if the property $Name of the object $dog was indeed set.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.