I'm coding a small piece for a larger project that will read a CSV file and store the information in a class. I'm storing each instance of the class in an array.
So far, all I'm trying to do is read each line of the CSV, create a new class instance with that info, and then display the info using a class function I created.
I have two questions:
first, when building the constructor, I originally tried using $this->$property
but I got undefined variable errors for each property when I did that. I took out $this and it seemed to work alright. I'm wondering why $this
didn't work there?
And now the error that I'm having is an undefined variable error for each time I try to access a variable to print it out in the displayInfo()
function of my class. I don't understand how the variable is undefined, they are properties of the class and they were initialized using the constructor.
Here's my code:
<?php
class Course {
public $crn;
public $title;
public $instructor;
public $section;
public $location;
public $time;
public $days;
function __construct($arg_crn, $arg_title, $arg_instructor, $arg_section, $arg_location, $arg_time, $arg_days) {
$crn = $arg_crn;
$title = $arg_title;
$instructor = $arg_instructor;
$section = $arg_section;
$location = $arg_location;
$time = $arg_time;
$days = $arg_days;
}
public function displayInfo() {
echo ("
");
echo $crn;
echo (", ");
echo $title;
echo (", ");
echo $instructor;
echo (", ");
echo $section;
echo (", ");
echo $location;
echo (", ");
echo $time;
echo (", ");
echo $days;
echo ("<br/>");
}
}
?>
<?php
$fileName = "testCSV.txt";
$fp = fopen($fileName, "r");
$index = 0;
// get the next line of the CSV: this contains the headers
$fields = fgetcsv($fp);
// get the next line of the CSV, which contains the first course information
// $fields is an array holding each field of the line (where a field is separated by commas)
$fields = fgetcsv($fp);
while($fields) {
// if at the end of the file, fgetcsv returns false and the while loop will not execute
// the fields in the file are saved into the following indices in fields:
// 0: CRN
// 1: Title
// 2: Instructor
// 3: Section
// 4: Location
// 5: Time
// 6: Days
// add a new course to the array of courses using the information from fields
$Courses[$index] = new Course($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6]);
$Courses[$index]->displayInfo();
// get the next line and increment index
$fields = fgetcsv($fp);
$index++;
}
?>