Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aurorame's avatar

Share static array between controllers?

How i can share static array between controllers? I try to put it in trait, but when i try to use it i got error: Using '$this' when not in object context

0 likes
4 replies
aurorame's avatar

@aurelianspodarec

<?php

namespace App\Http\Controllers\Traits;

trait ArrayTraits
{

    public static function returnArray()
    {
        $array = [
            1 => [ "value1" ],
            2 => [ "value2" ],
            3 => [ "value3" ],
            4 => [ "value4" ],
            5 => [ "value5" ],
            6 => [ "value6" ],
        ];
		return $array;
    }

}
splatEric's avatar
Level 2

Did you try static::returnArray() ?

1 like
eterlinden's avatar

@aurorame For something like this, I would not bother making a trait - it's not the right use case for a trait.

Create yourself a config file and just drop your array in there. Do this in config/someconfig.php

And it should look like this:

return [
       'myconfigarrayname' => [   // <-- this is your main key for the entire array 
               'key1' => 'value1',
               'key2' => 'value2',
               //...etc
];

Then, wherever you want to use it or need it (since you want the entire array), you can just call it like this:

$someArrayYouWantToUse = config('myconfigarrayname');

And, if you would like to just get a specific key from the array in your config, just use dot notation.

   $myParameter = config('myconfigarrayname.key1');

Hope this helps

Please or to participate in this conversation.