1

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!

4
  • I think array_rand has 2 parameter, Have a look in here Commented Jul 5, 2017 at 3:08
  • @LongKim second parameter is optional, that's not it. Commented Jul 5, 2017 at 3:09
  • Try this private $ip_to_use = $this->ip_pool[array_rand($this->ip_pool, 1)]; Commented Jul 5, 2017 at 3:11
  • What is your PHP version? using $this when defining default values feels wrong. this logic might be more suitable in the constructor. Commented Jul 5, 2017 at 3:40

2 Answers 2

1

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

Comments

1

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! :)

3 Comments

then use it as $ip_to_use[0] to get the first element? BTW, private $ip_to_use = array_rand($this->ip_pool); is also marking a syntax error.
You can use it with just $ip_to_use. array_rand() without a second parameter only returns one random element from the array. You can specify how many elements to return with an optional secondary int parameter (so array_rand($this->ip_pool, 2) would return two random IP addresses) :)
private $ip_to_use = array_rand($this->ip_pool); is also showing a syntax error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.