Jump to content

php singleton class to read multidimensional array from txt file

Go to solution Solved by Ch0cu3r,

Recommended Posts

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);
            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>';


I get as a result:


        [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 ?

Edited by Maq
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.