0

I have a problem with the following code, I am trying to print the data of a student but I get the following error:

Fatal error: Uncaught Error: Cannot access private property Secretary::$students

If i put the attributes as public, it works correctly.

class Student {

    private $name;

    public function __construct($name){
        $this->name = $name;
    }

    public function getName(){
        return $this->name;
    }

}

class Secretary{

    private $students = array();

     public function printStudents(){

         foreach($this->students as $key=>$value){
             echo $value->name . " ";
         }
     }

}

$secretary = new Secretary();

// Add students.
$student = new student("Student1");
array_push($secretary->students,$student);

$secretary->printStudents();
  • 1
    You're trying to access a private class member outside of your class. What do you expect to happen? Make it public or move that logic inside of that class. – John Conde Jan 30 '19 at 19:57
  • You should also look at `array_push($secretary->students,$student);` You could add another method to `Secretary` to add a student. – Nigel Ren Jan 30 '19 at 20:14
  • why have `getName()` if you're not gonna use it outside the class to get the name? (this should answer your name problem) – 5ar Jan 30 '19 at 23:33
  • 1
    Possible duplicate of [What is the difference between public, private, and protected?](https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected) – Azar Jan 30 '19 at 23:57

3 Answers3

6

Student->name is a private data member. That means, by definition, you cannot access it outside of the definition of Student. That's basically the purpose of getName(), so you CAN access it outside the definition.

What you want to do is this:

foreach($this->students as $key=>$value){
    echo $value->getName() . " ";
}

This will act as expected.

If you want to know more about access modifiers, you can read about them here.

2

You need a setter function for this. You cannot directly access a private variable.

In Class Secretary you need a function AddStudent(Student $students);

This function will look like:

public function AddStudent(Student $student) {
    if (!$this->students->contains($student)) {
        $this->students[] = $student;
    }
    return $this;
}

Afterwards you can use your function 'printStudents' to printout all students.

1

You cannot access a private property of a class outside of its own scope. To achieve what you want, consider making a new method like so:

public function addStudent(Student $s): Secretary
{
    array_push($this->students, $s);
    return $this;
}

Then, you can append your new student to the Secretary.

$s = new Secretary();
$s->addStudent(new Student('Foo'));

$s->printStudents();

You can see a live demo of it working.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86