-3

From the documentation "Members declared protected can be accessed only within the class itself and by inheriting and parent classes". Which means the properties can be accessed directly from children classes if I'm not mistaken, but I can't seem to access the protected properties as shown below:

<?php

class Person {
  public $name;
  protected $email = 'na';
  protected $phone;
}

class Employee extends Person {

}

$employee = new Employee();
var_dump($employee); // does show $email as ["email":protected]
echo $employee->email;

I did some research and people tell you to use setter and getter which seems like a hack to me because doing so, there's no difference between private and protected any more.

yivi
  • 42,438
  • 18
  • 116
  • 138

1 Answers1

0

You only have access to protected properties within the classes. For access from the outside, you need a public property or a public method.

Example:

<?php

class Person {
  public $name;
  protected $email = 'na';
  protected $phone;
}

class Employee extends Person {
  public function getMail(){
    return $this->email;
  }
}

$employee = new Employee();

echo $employee->getMail();  //na
yivi
  • 42,438
  • 18
  • 116
  • 138
jspit
  • 7,276
  • 1
  • 9
  • 17