I want to have an object for a student that contains their name among other properties – one of these properties being their assignment. And for the assignment I want to create another object containing its details.
class Student {
private $id; // used for sql queries
private $name; // result from such query
public function __construct($id) {
$this->id = $id;
// get properties from db using the $id
}
public function getName() {
return $this->name;
}
}
class Assignment {
private $id; // used for sql queries
private $student; // result from query
private $details; // result from query
public function __construct($id) {
$this->id = $id;
// get properties from db using the $id
$this->student = new Student($row["studentId"]);
}
public function getDetails() {
return "{$this->student->getName()} needs to do {$this->details}";
}
}
$assignment = new Assignment($someId);
$assignment->getDetails();
But for some reason I'm not allowed to access the assignment when it's protected. The only way to make it work is to make it public, but isn't that bad practice?
Speaking of bad practice, what about the whole approach of $student->assignment->getDetails()
; would it be better practice to just make a getter for the assignment (i.e. $student->getAssignment()->getDetails()
) ?
Thanks in advance
EDIT: Basically, I just want to know whether I can make $this->student->getName()
work somehow, or whether it's better to use $this->getStudent()->getName()
.
The reason I'm confused about protected access is because I'm already in the assignment, and therefore I should have access to all properties, but I don't. I don't have access to $this->student
, nor its methods, even though it's a property.
What's going on here?