我正在從事一個必須使用 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
?>
我收到此錯誤:致命錯誤:常量運算式在第 118 行的 C:\xampp\htdocs\Tylersite\index.php 中包含無效操作
我知道回傳有效,因為我用 測驗了它print_r,包括添加一個陣列編號,就像我對那個變數值所做的那樣,以獲得特定的陣列值。所以我一定不能正確呼叫該函式實體。我嘗試了各種方法,包括洗掉$this關鍵字,因為我不確定我是否需要它,但事實是我真的不知道該怎么做,而且我很難找到有關正確語法的檔案。有誰知道該怎么做?
uj5u.com熱心網友回復:
使用建構式的示例
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460258.html
上一篇:根據年份重置為默認值
