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;
1
  • 1
    I would convert this to a static function. The function itself can make sure that the list is only fetched once. Commented Apr 3, 2019 at 5:10

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm still getting the same error. I;ve updated the question, not sure if it helps. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.