Jump to content

& Functions


Drezard

Recommended Posts

I am currently reading the Zend Certification book. It talks about functions starting with a &. But, I dont quite understand what it means. When do you put a & at the front of a function?

 

The example it gives is:

 

function &query($sql)
{
$result = mysql_query($sql);
return $result;
}
// The following is incorrect and will cause PHP to emit a notice when called.
function &getHello()
{
return "Hello World";
}
// This will also cause the warning to be issued when called
function &test()
{
echo ’This is a test’;
}

 

Thanks, Daniel

Link to comment
Share on other sites

You can't use an & in front of a function. The & is used to call a variable by reference. It can be used with functions that return references.

<?php
$var1 = 'test';
$var2 =& $var;
function test_function($v) {
    if($v)
        return $v;
}
$var3 =& test_function($var2);
?>

A functions argument can reference a variable

<?php
$foo = 'test';
function change_var(&$var) {
    $var .= ' var';
}
change_var($foo);
echo $foo;// displays: test var
?>

Link to comment
Share on other sites

Yes you can use & in front of a function.  But very few people do because it usually doesn't make sense.

 

The only situation I can think of when return by reference makes sense is when dealing with arrays.  The examples in Drezard's post, there seems to be no reason why you would return a mysql result be reference.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.