Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.3 accessing array key from object getter

Tags:

arrays

object

php

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?

like image 853
Davor Avatar asked Sep 02 '26 15:09

Davor


2 Answers

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.

like image 69
Karo Avatar answered Sep 04 '26 05:09

Karo


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)

like image 37
Spudley Avatar answered Sep 04 '26 05:09

Spudley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!