0

I have following code in my class called lang.php:

<?php $GLOBALS['app_list_strings']['country']=array (
.....
)


    ...
?>

These array is not defined inside any function and class. I need to get these array values in other controller class. (For example, AdminController.php). How can I access these array values?($GLOBALS['app_list_strings']['country'])

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
phpdev
  • 511
  • 4
  • 22

1 Answers1

1

You can just inject your other class into your AdminController class and set up a get method to fetch the array(s) you need. Presumably you have your class set up like so (obviously there would be more script):

class Lang
    {
        public function someMethod()
            {
                $array =  array(
                    'app_list_strings'=>array(
                        'country'=>array(
                            'k1'=>'val1',
                            'k2'=>'v2'
                        )
                    )
                );
            }
    }

If you add a private parameter and a method you can extract that array:

class Lang
    {
        # Create parameter
        private $array;
        # Whatever method contains the array
        public function someMethod()
            {
                # use $this here
                $this->array = array(
                    'app_list_strings'=>array(
                        'country'=>array(
                            'k1'=>'val1',
                            'k2'=>'v2'
                        )
                    )
                );
                # I am just returning self for sake of demonstration.
                return $this;
            }
        # Returns the array
        public function getArray()
            {
                return $this->array;
            }
    }

class AdminController
    {
        # Inject your other class
        public function whateverMethod(Lang $lang)
            {
                # Retrieve array from getArray() method
                print_r($lang->someMethod()->getArray());
            }
    }

To use:

<?php
$AdminController = new AdminController();
$AdminController-> whateverMethod(new Lang());

To get the array just in general:

<?php
$Lang = new Lang();
print_r($Lang->someMethod()->getArray());

If the classes are far removed from each other, in that they are called from different areas of your script and they can not be injected like demonstrated, you can change private $array to private static $array and assign self::$array = array(...etc. then return self::$array. Because it's static it will persist through the script. Last way would be to save to $_SESSION, but that may not be the most desirable solution.

Rasclatt
  • 12,498
  • 3
  • 25
  • 33