0

I'm creating a class in my WordPress template and I have a multidimensional array as protected member. The array at second level contains some email addresses as string and I want to get those emails through a foreach loop. The code is like below.

class myclass {
  private $arr = array(
    'emails' => array(
      'someone@example.com',
      'someone@example.com',
      'someone@example.com'
    )
  );
  protected $emails = array();
  foreach($this->arr['emails'] as $email) {
    $this->emails[] .= $email
  }
}

PHP Giving Error

Parse error: syntax error, unexpected for (T_FOR), expecting function (T_FUNCTION) or const (T_CONST) in C:\xampp\htdocs\wp-content\themes\mytheme\functions.php on line no need of this

closed as off-topic by Jacob Peattie, fuxia Dec 23 '17 at 11:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

1

You can't have code directly in the class definition. If you want it on instantiation, put it in the __construct function.

Also, be aware that you were missing a semicolon and .= is used to append to strings, not to add to arrays. I've fixed those as well:

<?php
class myclass {
  private $arr = array(
    'emails' => array(
      'someone@example.com',
      'someone@example.com',
      'someone@example.com'
    )
  );
  protected $emails = array();

  function __construct() {
    foreach($this->arr['emails'] as $email) {
        $emails[] = $email;
      }
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.