Global variables are frowned upon, and often using a static variable is recommended in it's place.
I need to be able to have the variables I get from the CSV file, accessible to any function within the php file.
Is this possible to do if I'm parsing a CSV file for the variables?
For example, how can I make $name
and $table
available to any function in the file?:
<?php
$f_pointer=fopen("student.csv","r"); // file pointer
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
$name = $data[0];
$table = $data[3];
echo print_r($ar); // print the array
echo "<br>";
}
?>
You can create a class from this function and return the results from this as a member function. We can use a multidimensional array as our return.
class My_Class{
public $array;
public function get()
{
$this->array = array();
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
$name = $data[0];
$table = $data[3];
$this->array[] = array(
'name' => $name,
'table' => $table,
'ar' => $ar
);
}
return $this->array();
}
}
Then you can initialize it in this way:
$My_Class = new My_Class;
echo '<pre>', print_r($My_Class->get(), true),'</pre>';
Which will produce a multidimensional array with the data that we iterated through in our while case.