3

I have a Form object $form. One of its variables is a Field object which represents all fields and is an array (e.g $this->field['fieldname']). The getter is $form->fields().

To access a specific field method (to make it required or not for example) I use $form->fields()['fieldname'] which works on localhost with wamp but on the server throws this error:

Parse error: syntax error, unexpected '[' in (...)

I have PHP 5.3 on the server and because I reinstalled wamp and forgot to change it back to 5.3, wamp runs PHP 5.4. So I guess this is the reason for the error.

How can I access an object method, which returns an array, by the array key with PHP 5.3?

6

3 Answers 3

3

Array dereferencing is possible as of PHP 5.4, not 5.3

PHP.net:

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

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

1 Comment

thanks. Unfortunately that means I cannot modify my $form object (since the $form->fields() has a lot of setters) because using temporary variables would only be useful for display.
2

Array dereferencing as described in the question is a feature that was only added in PHP 5.4. PHP 5.3 cannot do this.

echo $form->fields()['fieldname']

So this code will work in PHP 5.4 and higher.

In order to make this work in PHP 5.3, you need to do one of the following:

  1. Use a temporary variable:

    $temp = $form->fields()
    echo $temp['fieldname'];
    
  2. Output the fields array as an object property rather than from a method:
    ie this....

    echo $form->fields['fieldname']
    

    ...is perfectly valid.

  3. Or, of course, you could upgrade your server to PHP 5.4. Bear in mind that 5.3 will be declared end-of-life relatively soon, now that 5.5 has been released, so you'll be wanting to upgrade sooner or later anyway; maybe this is your cue to do? (and don't worry about it; the upgrade path from 5.3 to 5.4 is pretty easy; there's nothing really that will break, except things that were deprecated anyway)

1 Comment

Cheers! I need to convince my host to give me 5.4, they only offer it for new accounts which is slightly ridiculous...
1

As mentioned array dereferencing is only possible in 5.4 or greater. But you can save the object and later on access the fields:

$fields=$form->fields();
$value=$fields['fieldname']
...

AFAIK there is no other option.

Comments

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.