PHP function question

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

    PHP function question

    When writing a function that takes in a variable number of parameters and
    processing it using func_get_args or a similar technique, I'm assuming that
    one is only able to use the pass by value method of parameter passing. Can
    someone confirm or deny this for me?

    Below is a trivial example of what I'm talking about. I'm assuming the
    function below does nothing useful.

    <?php

    function squares( )
    {
    $params=functio n_get_args();
    $numparams= func_num_args() ;
    for ($i=0;$i<$numpa rams;$i++)
    $params[$i]*=$params[$i];
    }

    ?>


  • Pedro Graca

    #2
    Re: PHP function question

    ["Followup-To:" header set to comp.lang.php.]
    Tony wrote:[color=blue]
    > When writing a function that takes in a variable number of parameters and
    > processing it using func_get_args or a similar technique, I'm assuming that
    > one is only able to use the pass by value method of parameter passing. Can
    > someone confirm or deny this for me?[/color]

    I think you're right.
    [color=blue]
    > Below is a trivial example of what I'm talking about. I'm assuming the
    > function below does nothing useful.
    >
    ><?php
    >
    > function squares( )
    > {
    > $params=functio n_get_args();
    > $numparams= func_num_args() ;
    > for ($i=0;$i<$numpa rams;$i++)
    > $params[$i]*=$params[$i];
    > }
    >
    > ?>[/color]


    But you can use the $GLOBALS variable to pretend you're passing by
    reference.

    Here's a way

    <?php
    function squares() {
    $parms = func_get_args() ;
    $nparms = func_num_args() ;
    $retval = array(); // return array

    for ($i = 0; $i < $nparms; ++$i)
    if ($parms[$i]{0} == '$')
    $GLOBALS[substr($parms[$i], 1)] *=
    $GLOBALS[substr($parms[$i], 1)];
    else $retval[] = $parms[$i] * $parms[$i];
    return $retval;
    }

    $a = 6; $b = 7; $c = 8;
    $res = squares($a, "$b", '$c');

    print_r($res);
    echo $c;
    ?>
    --
    --= my mail box only accepts =--
    --= Content-Type: text/plain =--
    --= Size below 10001 bytes =--

    Comment

    Working...