Search code examples
phpclassprivate

Nested classes error


I am trying to nest a class inside of another class in PHP, and display the data via HTML. I have a Question Class, and inside of that class, i create a User object. The user object contains the information for the user who created the question. For some reason, I am getting "( ! ) Fatal error: Cannot access private property Question::$user" in my output. Nothing that I can tell is private that would be preventing me from pulling the data. Here is a bit of code:

class Question extends Model {
    private $user;
    private $content;
    private $title; 
    private $tags;
    private $date;
public function __construct($user, $content, $title, $tags, $date) {
    parent::__construct();
    $this -> setUser($user);
    $this -> setContent($content);
    $this -> setTitle($title);
    $this -> setTags($tags);
    $this -> setDate($date);
}

public function getUser() {
    return $this -> user;
}

public function setUser($user) {
    $this -> user = User::findUser($user);
    return $this;
}

Then this is my User class:

class User extends Model {
    private $email;
    private $password; 
    private $fname;
    private $lname;

    public function __construct($email, $password, $fname, $lname) {
        parent::__construct();
        $this -> setEmail($email);
        $this -> setPassword($password);
        $this -> setFname($fname);
        $this -> setLname($lname);
    }

The functions that create the question and user objects are as follows:

private static function makeQuestionFromRow($row) {
        $question = new Question($row['user_id'], $row['quest_Content'], $row['quest_Title'], $row['quest_Tags'], $row['quest_DatePosted']);
        $question -> id = $row['quest_ID'];
        return $question;
    }

private static function makeUserFromRow($row) {
        $user = new User($row['user_email'], $row['user_pwd'], $row['user_fname'], $row['user_lname']);
        $user -> id = $row['user_id'];
        return $user;
    }

And both are subclasses of Model:

class Model {
    protected $id;

    public function __construct() {

    }

    public function getId() {
        return $this -> id;
    }

I am trying to display the user's first and last name, and make it a link to the user page, which views the user info. So my code to do that is:

<b>Date Posted: </b>{{date("m/d/Y", strtotime($question->getDate()))}} by <a href="@@user/view/{{$question->user->getId()}}@@"> TEST</a> <br /><br />

The date code comes out correct, however the user id is not coming out and linking to "test" above. I'm not sure if I am doing something syntax wrong or what. If someone could help me out, I would appreciate it.

This is homework. Not trying to get over on anyone. Thanks again.


Solution

  • Instead of calling $question->user in your template, you need to call $question->getUser(). Learn about visibility in PHP for more information.