I want to create a singleton class that read multidimensional array from txt file and flatten the array retrieved.
This is what I have tried so far:
class singleton {
protected static $instance = null;
public static function getInstance() {
if (!isset(static::$instance)) {
static::$instance = new static;
}
return static::$instance;
}
public static function flattenArray($array) {
$return = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $value) {
$return[] = $value;
}
return $return;
}
public static function loadFile($path) {
$file_handle = fopen($path, "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$rawarray[] = $line;
}
$flattedarray = self::flattenArray($rawarray);
fclose($file_handle);
return $flattedarray;
}
With the txt file containing:
array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')
I run the class with:
include 'singleton.php';
$singleton = singleton::getInstance();
$flattedarray = $singleton->loadFile("file.txt");
echo '<pre>';
print_r($flattedarray);
echo'</pre>';
I get as a result:
Array
(
[0] => array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')
)
Which is the same array found in the txt file.
how can i do it without using eval.
What am I doing wrong ?