Php 访问类的属性
我正在为一个更大的项目编写一小段代码,该项目将读取CSV文件并将信息存储在类中。我将类的每个实例存储在一个数组中 到目前为止,我所要做的就是读取CSV的每一行,用这些信息创建一个新的类实例,然后使用我创建的类函数显示这些信息 我有两个问题: 首先,在构建构造函数时,我最初尝试使用Php 访问类的属性,php,class,Php,Class,我正在为一个更大的项目编写一小段代码,该项目将读取CSV文件并将信息存储在类中。我将类的每个实例存储在一个数组中 到目前为止,我所要做的就是读取CSV的每一行,用这些信息创建一个新的类实例,然后使用我创建的类函数显示这些信息 我有两个问题: 首先,在构建构造函数时,我最初尝试使用$this->$property,但当我这样做时,每个属性都出现了未定义的变量错误。我拿出这美元,它似乎工作正常。我想知道为什么$this在那里不起作用 现在我遇到的错误是一个未定义的变量错误,每次我试图在类的displ
$this->$property
,但当我这样做时,每个属性都出现了未定义的变量错误。我拿出这美元,它似乎工作正常。我想知道为什么$this
在那里不起作用
现在我遇到的错误是一个未定义的变量错误,每次我试图在类的displayInfo()
函数中访问一个变量以将其打印出来。我不明白变量是如何定义的,它们是类的属性,并且是使用构造函数初始化的
这是我的密码:
<?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 ("\n");
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++;
}
?>
正如Mark Baker提到的,可以使用
$this->crn
访问实例变量,请遵循相同的方法并阅读一些关于PHP中OOPS的教程,因为您太新了,无法在这里询问任何问题
您尝试使用$this->$property
访问属性,该属性应为$this->property
一些教程:
$this->crn
等。这些是实例变量,作用域为实例;不是作用于函数的变量。。。。。请注意,它是$this->crn
,而不是$this->$crn
。您应该阅读一些关于如何在PHP中使用OOPS的教程。