0

I'm trying to set a private variable array on my class. But I'm getting an error. Is this even possible? In other words, can I define a variable with a key - or is it bad practice?

class SomeClass { private $result['results'] = array(); .... 

Error: Parse error: syntax error, unexpected '[', expecting ',' or ';'

3
  • not sure what you are planning to do... Commented Jan 20, 2016 at 0:42
  • I'm building an object, adding values to the results array. I just need to access this in a separate method, so wanted to set it as a class variable. Commented Jan 20, 2016 at 0:43
  • Just define private $result = array(); If you want to add sub arrays fo rit when you need them Commented Jan 20, 2016 at 0:45

2 Answers 2

3

I think it is possible but not in the way you are doing it. try

private $result = array(); 

and then, you can create a function to push things in the array, something like

public function __set($key, $value){ $this->result[$key] = $value; }

then, push what you want into the array calling your function

__set('private','this is my private array'); 
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to access the key 'results' of that property result later, you should declare it like this first:

class SomeClass { private $result = array( 'results' => array(), ); .... 

Although you can also have only defined the property result and added the results key later, but you can run on problems like 'undefined index ...' exceptions if you tried to access results before adding the 'results' key to the result property.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.