4

I want to do something like this without using extra variables:

class className {
  public static function func(){
    return array('true','val2');
  }
}

if(className::func()[0]) {
  echo 'doğru';
} else {
  echo 'Yanlış';
}
hakre
  • 193,403
  • 52
  • 435
  • 836
Lupus
  • 1,519
  • 3
  • 21
  • 38
  • 4
    PHP does not support array dereferencing this way. Why can't you use an intermediate variable? – Felix Kling Jan 18 '12 at 16:29
  • @Felix Kling PHP 5.4 will have that feature: http://css.dzone.com/polls/what-new-feature-php-54 – feeela Jan 18 '12 at 16:31
  • possible duplicate of [Access an Array Returned by a Function](http://stackoverflow.com/questions/1664362/), [Access array returned by a function in php](http://stackoverflow.com/questions/1459377/) – outis Jan 19 '12 at 10:51

4 Answers4

10

className::func()[0] is called array dereferencing, and is not valid syntax in all PHP versions. It will be is available starting in PHP 5.4, currently in beta, released March 2012. For earlier PHP version, you will need to use an extra variable somewhere to store the array returned from className::func().

See the PHP 5.4 Array documentation for implementation details.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
7

Array Deferencing is not currently available in PHP. It is on the table for PHP 5.4.

Until then, you would need the extra variable:

$arr = className::func();
if($arr[0]){
    echo 'doğru';
}else{
   echo 'Yanlış';
}
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
2

Well,you can return an object in your method instead. something like:

class className{
      public static function func(){
          return (object)array('true'=>'true','val2'=>'val2');
      }
}

echo className::func()->true;//Extra variables go away =)
Lake
  • 813
  • 4
  • 6
1

As the others noted, you currently cannot do it this way. If you really cannot use an temporary variable (although I don't see a reason not to use one) you could use

if(current(className::func())) // or next() or reset()

But make sure you read the documentation about these functions to treat empty arrays properly.

Reference: current

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • You cannot (or at least, should not) pass the result of an expression directly to `array_shift()` because it takes the input array argument by reference, since it modifies the input array. The same is true of `current()`, but to a lesser extent as I believe this does not modify the input array. – DaveRandom Jan 18 '12 at 16:40
  • @DaveRandom: And why should this be avoided then? But you are right, `array_shift` does not work. – Felix Kling Jan 18 '12 at 16:43
  • Because if you look at the docs, it does say that (for some reason) `current()` takes it's argument by reference. This *should* generate an `E_STRICT` as it does with `array_shift()` although I have just tried it and actually it doesn't so it may be that the docs are wrong. – DaveRandom Jan 18 '12 at 16:53