我正在做一个大学项目,必须使用CSV文件来创建表的值。它必须有一个类,它必须有特定的类变量(其中一个我已经创建用于测试)。只有变量被指定为必须成为类的一部分,但我认为最好将函数包装在类中(除非有人有不同的意见)。
基本上,我想使用类函数为类变量创建值。下面是我的脚本(参考注释进行解释):
<?php
class productRow {
function make_table_row($i) {
$row = 1;
$tablerows = [];
if (($input = fopen("input.csv", "r")) !== FALSE) {
while (($tabledata = fgetcsv($input, 1000, ",")) !== FALSE) { //cycles through the rows of data creating arrays
if ($row == 1) {
$row++;
continue; //skips the first row because it's a header row I don't want on my input
}
$tablerows[] = $tabledata; //uses the roles to populate a multidimensional array
$row++;
}
fclose($input);
return $tablerows[$i]; //uses the $i argument to return one of the row arrays
}
}
var $itemNumber = this->make_table_row($i)[0]; //Line 118: calls make_table_row function to get the first item from the row returned
}
$pr1 = new productRow;
echo $pr1->make_table_row(1); //calls the function from within the class
?>
我得到这个错误:致命错误:常量表达式包含无效的操作在C:xampphtdocsTylersiteindex.php在第118行
我知道返回有效,因为我用print_r
测试了它,包括添加数组号,就像我对该变量值所做的那样,以获得特定的数组值。所以我一定没有正确调用那个函数实例。我尝试了各种各样的事情,包括删除$this
关键字,因为我不确定我需要它,但事实是我真的不知道如何做到这一点,我有困难找到正确的语法文档。有人知道该怎么做吗?
使用构造函数的例子
class productRow {
var $itemNumber = []; // default value doesn't matter as it will change in __construct
public function __construct($i) {
$this->itemNumber = $this->make_table_row($i)[0];
}
function make_table_row($i) {
$row = 1;
$tablerows = [];
if (($input = fopen("input.csv", "r")) === FALSE) {
// return early - reduces indentation
return;
}
while (($tabledata = fgetcsv($input, 1000, ",")) !== FALSE) { //cycles through the rows of data creating arrays
if ($row == 1) {
$row++;
continue; //skips the first row because it's a header row I don't want on my input
}
$tablerows[] = $tabledata; //uses the roles to populate a multidimensional array
$row++;
}
fclose($input);
return $tablerows[$i]; //uses the $i argument to return one of the row arrays
}
}
$pr1 = new productRow(1);
var_dump($pr1->make_table_row(1));