Skip to main content

PHP: Learning OOP

Below is one of the first classes I've built. I started creating my functions like so:

public function getCourseInfoByID($id) { } 

Requiring the user to pass a course ID. I've recently modified it to assign the course ID (and $course_info - an array to reference each element from the DB) in the constructor, and I'd like to get some feedback if I'm doing it properly (I figured $course->getCourseInfo(); was much better than $course->getCourseInfoByID(1);):

class Course {
    var $course_id;
    var $course_info;

    // The constructor just sets the database object
    public function __construct($mysqli, $course_id = NULL) {
        global $error;
    
        $this->mysqli = $mysqli;
    
        // If course_id is present (referencing a course instead of creating one, let's validate it and assign the course_id to the object)
        if($course_id != NULL) {
            if(! $course_info = $this->getCourseInfo($course_id)) {
                $error[] = "Invalid Course ID";
                setError();
                return FALSE;               
            }

            $this->course_id = $course_id;
            $this->course_info = $course_info;
        }
    }

    public function getCourseInfo($id = NULL) {
    
        if($id == NULL) {
            $id = $this->course_id;
        }
    
        $result = $this->mysqli->query("SELECT courses.*, students.first_name, students.last_name, course_types.name as course_type_name
                                    FROM courses as courses
                                    JOIN students as students on students.id=courses.instructor_id
                                    JOIN course_types as course_types on course_types.id=courses.course_type_id
                                    WHERE courses.id='$id'");
                                    
        $course_info = $result->fetch_array(MYSQL_ASSOC);
    
        // If found, return the student object
        if($course_info) {
            return $course_info;
        } 
        return FALSE;
    }

    public function displayCourseInfo($id = NULL) {
        global $error;
    
        if($id == NULL) {
            $id = $this->course_id;
        }

        // HTML to display each element of $this->course_info[]
        // acccessible anytime by doing: $course->displayCourseInfo() in the script
    }

}
execv
  • 201
  • 1
  • 3