3

so I have this class

class A{

  public $something['aaa'] = 'soemthing';

}

but then it complains that there is syntax error....

how can I set class variables in PHP as an associative array?

2 Answers 2

3

Can't say I'm right saying this.. but you might have to declare it in the constructor:

class A{

  public $something; // or $something = array();

  function __construct($something){
     $this->something['aaa'] = $something;
  }

}
Sign up to request clarification or add additional context in comments.

Comments

1

That's strange. I don't think that's invalid syntax but it is throwing an error on my end. Maybe the parsre just isn't equipped to handle an property being initialized in that way. When I tried the following equivalent initialization it seemed to work just fine:

<?php
class A {
  public $something = array("aaa" => "something");
}
?>

1 Comment

The syntax in the opening post is not invalid per se, but it´s incomplete. It´s assigning the value 'soemthing' to the key 'aaa' in the array $something... but nowhere it´s $something declared as an array. In your code, you are expliclty declaring $something as an array, and also asigning that key => value at the same time, but the important part is the declaration.

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.