Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP syntax for dereferencing function result

Background

In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring a new variable to hold the function result.

In PHP, however, this does not appear to be so simple:

example1 (function result is an array)

<?php  function foobar(){     return preg_split('/\s+/', 'zero one two three four five'); }  // can php say "zero"?  /// print( foobar()[0] ); /// <-- nope /// print( &foobar()[0] );     /// <-- nope /// print( &foobar()->[0] );     /// <-- nope /// print( "${foobar()}[0]" );    /// <-- nope ?> 

example2 (function result is an object)

<?php     function zoobar(){   // NOTE: casting (object) Array() has other problems in PHP   // see e.g., http://stackoverflow.com/questions/1869812   $vout   = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',);   return $vout; }  //  can php say "zero"?        //  print zoobar()->0;         //  <- nope (parse error)       //  print zoobar()->{0};       //  <- nope                     //  print zoobar()->{'0'};     //  <- nope                     //  $vtemp = zoobar();         //  does using a variable help? //  print $vtemp->{0};         //  <- nope      
like image 799
dreftymac Avatar asked Apr 13 '09 01:04

dreftymac


People also ask

What does => mean in PHP?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .

What is array Dereferencing in PHP?

Array Dereferencing is really very good feature added in PHP 5.4. With this you can directly access an array object directly of a method a functions. Now we can say that no more temporary variables in php now.


1 Answers

PHP can not access array results from a function. Some people call this an issue, some just accept this as how the language is designed. So PHP makes you create unessential variables just to extract the data you need.

So you need to do.

$var = foobar(); print($var[0]); 
like image 93
Ólafur Waage Avatar answered Sep 29 '22 08:09

Ólafur Waage