Fgetcsv return value not as expected when calling inside a class method

Hi I have started a new project and starting simple, made a class and 3 functions in the class. One opens a file, second reads a line from the file using fgetcsv() and third function closes the file.

The function that reads the line from the file is this:

public function readCSVRow()
{
    if ($this->$arr_currentRow = fgetcsv($this->$file_CSV, 1000, ",", '"'))
        return TRUE;
    else
    {
        echo "readCSVRow failed to get data.<br/>\n";
        return FALSE;
    }
}

$this->$file_CSV is the file resource returned by fopen()
$this->arr_currentRow is an array that holds the return value of fgetcsv

in my “main” code I have gotten down to testing the readCSVRow method one read at a time. The first time it is called, it works as expected. The second time I call it, it doesn’t get any data from fgetcsv.

if ($parser->openFileCSV() == TRUE)
{
    if ($parser->readCSVRow() == TRUE)
        print_r($parser->$arr_currentRow);
    if ($parser->readCSVRow() == TRUE)
        print_r($parser->$arr_currentRow);
}
else
{
    echo "File open failed.<br/>\n";
}

If I use fgetcsv() outside of the class, it will read from the CSV file and display all the data I want as expected.

I have not used OOP in PHP before this. Is there something about what I’m doing with my class that is incorrect? All the class members I am trying to access from the main code are publicly accessible.

you should get an unexpected variable error for that: $arr_currentRow ... $file_CSV

I don’t get any errors that halt the execution.

Output:
http://beardeddonkey.com/mpuv/mpuvClass.php

Full source:
https://pastebin.com/cfqPZFxL

then your PHP is misconfigured, i instantly get

PHP Notice: Undefined variable: str_inputFileCSV in scratch_35.php on line 48

and that makes sense reagarding your code. So you should at least set

error_reporting(-1);
ini_set('display_errors', 1);

so the answer is not to use $ when referencing object members.

$objectName->memberName
not
$objectName->$memberName

restriction: in YOUR case. Otherwise its technically valid and there are use-cases for it.

Sponsor our Newsletter | Privacy Policy | Terms of Service