简体   繁体   中英

Why am I getting a syntax error in setting this Array into a class?

I am getting a syntax error but I don;t understand exactly why, here is my code:

class VerifyEmail {

     private $ip_pool = array("167.114.48.81","167.114.48.82"....);
     private $ip_to_use = $this->ip_pool[array_rand($this->ip_pool)]; //ERROR HERE
     .....

I tried also:

     private $ip_to_use = $ip_pool[array_rand($ip_pool)];

with no luck.

Am I missing something? Or you cannot do an array rand of a private variable when setting up the variables?

Thanks!

You're currently trying to access the array as an index of the array itself.

Considering you're just trying to assign one string from within the $ip_pool array to $ip_to_use , all you need is $ip_to_use = array_rand($this->ip_pool) .

class VerifyEmail {  
  private $ip_pool = array("167.114.48.81","167.114.48.82"....);
  private $ip_to_use = array_rand($this->ip_pool);
  ...  

Hope this helps! :)

I get the following notice in my IDE for that line

expression is not allowed as a field default value

I can only suggest moving your rand call into the __construct() method

class VerifyEmail {

  private $ip_pool = array( "167.114.48.81", "167.114.48.82");
  private $ip_to_use;

  public function __construct() {
    $this->ip_to_use = $this->ip_pool[ array_rand( $this->ip_pool ) ];
  }

}

var_dump( new VerifyEmail() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM