tags:

views:

43

answers:

1
+1  Q: 

PHP syntax error

Hi,

Can anyone explain to me why the following is resulting in a syntax error (unexpected '=')?

protected function processDates()
  {
       foreach($this->dates as $name => $unitprefix)     
       {
            $this->$unitprefix.'year' = '';   
            $this->$unitprefix.'month' = '';
            $this->$unitprefix.'day' = '';
       }
  }

Obviously I'm not going to leave these values blank but before I continue, I need to fix the current issue.

Any advice appreciated.

Thanks.

+7  A: 

Try

$this->${$unitprefix.'year'} = '';

But to give a better advise it would be good to know the properties of your class and what $unitprefix contains.

Reference: Variable variables

To give more details:
Your code is not clear to the parser in the way your write it. Assuming $unitprefix = 'foo', your code can be interpreted in two ways:

  1. Get the value of $this->$unitprefix , i.e. $this->foo and append 'year'. Then your code would result in (with $this->foo = bar):

    'baryear' = '';
    I guess this is what the parser is doing as this corresponds to an evaluation of the code from left to right.

  2. Append 'year' to $unitprefix and get the property with the resulting name, i.e. the resulting code is:

    $this->fooyear = '';

The second is the beviour you want to have but without ${} the parser does not know what to do.

Felix Kling
Thanks for your help.
Dan