0

I'm fairly new to PHP and I am trying to return an array from a class function and then access its values like so:

  <?php 
    class Foo
        {
            private $access;

            public function setAccess($access)
            {
                $this->access = $access;
            }


            public function getAccess()
            {
                return $this->access;
            }
        }


$var = new Foo();
$var->setAccess(array(1,2,3,4));

$var2 = $var->getAccess()[2];

echo $var2;

?>

When I try to run a page with this code, I get the following:

Parse error: syntax error, unexpected '[' in arraytest.php on line 22

How can I access the values for my private arrays in my class?

Sandoichi
  • 254
  • 5
  • 14

2 Answers2

2

This:

$var2 = $var->getAccess()[2];

can't be done in PHP before version 5.4 (this feature is called array dereferencing). At the moment you have to do something like this:

$var2 = $var->getAccess();
$var2 = $var2[2];
Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
  • Thanks for letting me know the PHP version and the name (array dereferencing). I had a hard time finding related questions. – Sandoichi Nov 10 '11 at 22:58
1

you can't call an array value directly like that, you'd have to write this:

$access = $var->getAccess();
$var2 = $access[2];

alternatively, you could add a function like this to your class.

public function getAccessValue($key) {
  return $this->access[$key];
}
GSto
  • 41,512
  • 37
  • 133
  • 184
  • Ah, I originally wrote a function like that however I was hoping there was a better method. I will just store the array into a variable first then dereference, thanks. – Sandoichi Nov 10 '11 at 22:56