perl style in php ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • crub

    perl style in php ?

    Often I just want to be able to get at a single element from a
    function that returns an array. For example, if I just want the
    current year I need to write:


    $today = getdate();
    $year = $today['year'];


    Call me lazy but this is two steps to return a single value.
    In perl I can nest these two step together into something like:

    $year = ( $getdate() )['year'];


    I've tried to get several variations of this to work in php but I
    don't seem to be having any luck.

    Is this style possible in php?

    Thanks,
    crub
  • Janwillem Borleffs

    #2
    Re: perl style in php ?

    crub wrote:[color=blue]
    > Call me lazy but this is two steps to return a single value.
    > In perl I can nest these two step together into something like:
    >
    > $year = ( $getdate() )['year'];
    >
    >
    > I've tried to get several variations of this to work in php but I
    > don't seem to be having any luck.
    >
    > Is this style possible in php?[/color]

    Not quite, although PHP 5 introduces object dereferencing, which comes
    close:

    <?php

    function array2object($a rray) {
    $obj = new stdClass;

    foreach ($array as $k => $v) {
    $obj->$k = $v;
    }

    return $obj;
    }

    $array = array('name' => 'joe');
    print array2object($a rray)->name;

    ?>

    Indexed arrays can be parsed the usual way through the list() function.


    JW



    Comment

    • Chung Leong

      #3
      Re: perl style in php ?

      crub@volcanomai l.com (crub) wrote in message news:<e41b87b8. 0410310759.7d10 88fe@posting.go ogle.com>...[color=blue]
      > Often I just want to be able to get at a single element from a
      > function that returns an array. For example, if I just want the
      > current year I need to write:
      >
      >
      > $today = getdate();
      > $year = $today['year'];
      >
      >
      > Call me lazy but this is two steps to return a single value.
      > In perl I can nest these two step together into something like:
      >
      > $year = ( $getdate() )['year'];
      >
      >
      > I've tried to get several variations of this to work in php but I
      > don't seem to be having any luck.
      >
      > Is this style possible in php?[/color]

      No. What I often do in this situation is use extract(). Example:

      extract(getdate ());
      // $year, $mon, $seconds, etc. are now set

      Comment

      Working...