A 'missing' PHP primitive?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




Hi, I'm wondering if there is any built-in PHP primitives to perform the same task as this simple, almost trivial function:

function get(&$var) {
     return $var;
}

?


It is useful for accessing arrays where some fields may be unset. For example:

************************************************

<?php


function get(&$var) {
     return $var;
}

$arr = array();
$arr[5] = 'sam';
$arr[2] = 'chris';
$arr[3] = null;

$fromGet5 =  get($arr[5]);
$fromGet1 = get($arr[1]);

echo "Value of fromGet5 is $fromGet5\n";
echo "Value of fromGet1 is $fromGet1\n";

$fromGet5 = 'fred';

echo "Value of fromGet5 is now $fromGet5\n";

echo "Value of arr[5] is still $arr[5]\n";

**************************************************


Assigning the value directly, without the function, as in <$fromGet1 = &$arr[1]> transfers the value & the reference, which is undesirable & likely to lead to hard to detect bugs. Assignment without a reference generates errors for undefined array keys.

The inline code (isset($arr[1]) ? $arr[1] : NULL) is cumbersome to keep typing over & over again & logically might be less efficient since it appears to fetch arr[1] twice, though there may be some hidden optimization.

It seems like there should be a built in primitive called 'get' or 'ifset' that does this task.

Wondering how others handle this issue & what I might be missing...






[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux