Page 1 of 1

Cannot pass parameter null by reference

Posted: Wed Aug 23, 2006 2:54 pm
by Ollie Saunders
I have this function:

Code: Select all

public function setSource(&$r_source)
{
    if ($r_source === null) {
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'POST':
                $this->_r_source =& $_POST;
                break;
            case 'GET':
                $this->_r_source =& $_GET;
            default:
                // REQUEST_METHOD is unreliable and use POST
                $this->_r_source =& $_POST;
        }
    } else if (is_array($r_source)) {
       $this->_r_source =& $r_source;
    } else {
        $errMsg = 'Source must be an array or null; ' . gettype($r_source) . ' given';
        throw new OF_Exception($errMsg, OF_Exception::TYPE_SCALAR);
    }
}
As you can see I'd like to be able to accept an array by reference or null. But you can't do that because:

Fatal error: Cannot pass parameter 1 by reference in /osis/lib/code/php/OF/Array.php on line 48

Other than two separate parameters is there anyway you can solve this?

Posted: Wed Aug 23, 2006 5:11 pm
by Chris Corbyn
You can't do:

Code: Select all

setSource(null);
But you can do:

Code: Select all

$x = null;
setSource($x);
You can't reference a constant.

Posted: Wed Aug 23, 2006 5:13 pm
by Ollie Saunders
but there is no way to allow setSource(null);?

Posted: Wed Aug 23, 2006 5:15 pm
by volka
not as reference.

as single line: setSource($x=null);

Posted: Wed Aug 23, 2006 5:17 pm
by Chris Corbyn
PHP5 supports this syntax:

Code: Select all

public function setSource(&$foo=null)
{
   //
}
But you can't explicitly pass null as a reference. PHP4 doesn't support the above.

If you think about it, it makes sense really... what would a null reference point to?

Posted: Wed Aug 23, 2006 5:18 pm
by Ollie Saunders
volka wrote:not as reference.

as single line: setSource($x=null);
I guess that will have to do. Thanks guys.

Posted: Wed Aug 23, 2006 5:20 pm
by Chris Corbyn
ole wrote:
volka wrote:not as reference.

as single line: setSource($x=null);
I guess that will have to do. Thanks guys.
The other approach is a bit cleaner in that setSource() without any args does what you need :)

Posted: Wed Aug 23, 2006 5:31 pm
by Ollie Saunders
Oh wow thanks for posting again. I missed that.