0

I have this variable as below in my class file.

public static $Whitelist = array(
        '10.10.10.1',
        '10.10.10.2',
        '10.10.10.5',
);

I'm trying to convert it so that I can have the list from my database instead of hard coding like below:

public static $Whitelist = IPWhitelist::getIPWhitelist();

However, it return an error saying that the syntax is wrong. How do i fix it? How come I can assign an array to it but not a function that also returns an array? Thanks.


EDIT: It actually contains 3 files here.. let me explain more.

File 1: (config modal file)

class Config{
    public static $Whitelist = IPWhitelist::getIPWhitelist();
}

File 2: (database modal file)

class IPWhitelist{
    public function getIPWhitelist($type = 1){
           //some database code here

            return $array_total_ips;
        }
}

File 3: (main file)

$ip_list = Config::$Whitelist;
nodeffect
  • 1,830
  • 5
  • 25
  • 42
  • 1
    I would convert this to a static function. The function itself can make sure that the list is only fetched once. – Evert Apr 03 '19 at 05:10

1 Answers1

2

Static properties obey the same rules as const expressions: it must be possible to evaluate the expression at compile time. Function calls cannot: they must happen at runtime.

You could instead use a static variable within the getIPWhitelist function to have it only fetch from the database once:

function getIPWhitelist()
{
  static $list = null;

  if(!$list) {
    // fetch from the database here (only executed once)
    $list = [
      '10.10.10.1',
      '10.10.10.2',
      '10.10.10.5',
    ];
  }

  return $list;
}
cfillion
  • 1,340
  • 11
  • 16