Hi, in the function declaration I see sometimes &$variable, sometimes just the normal form $variable. What is the difference?

Ah, another question: if there is written
function abc ($categorie=NULL) {...
That means that $categorie is empty with the beginning of the function?

Thanx,
Marenz.

Comments

doli’s picture

I'm starting writing in php, but usually difference between passing argument through reference (&$) and by $ is that when you pass argument through reference you work on original variable, means if you change it inside your function it's going to be changed outside of it as well, if you pass argument as a copy, function creates copy instance of this variable, and work on this copy, so if you change it in the function it won't be changed outside of it.

Second question is probably the default value, if you use your abc function like abc() omiting argument, then it will use $categorie variable set with the NULL value.

But as I said I'm just strating working with php, so would be good if someone could confirm what I wrote here.

cheers,
Marcin

Anonymous’s picture

(1.) ...why very often there is used a default "=" and then they ask for the value in the function, like in profile.pages.inc:

function tracker_page($account = NULL, $set_title = FALSE) {
  if ($account) {...}

Does this make any sense?! It is done like this in many other modules...

(2.) So the &$variable is the same as doing a return $variable at the and of the function?

heine’s picture

This allows one to use a function with and without arguments, eg tracker_page($user) and tracker_page() instead of tracker_page(NULL).

Also, many callbacks take their extra arguments from the path (foo/edit/ID) where foo_edit_page() listens to foo/edit and gets 14 as the first arg:

function foo_edit_page($id) {
}
// vs.
function foo_edit_page($id = NULL) {
}

The default makes sure that a user accessing foo/edit without providing an id doesn't generate a PHP error ("missing argument for function").

No, return $variable is not the same. The caller handles the return value of a function; it may discard it, assign it to another variable. Changing a variable passed by reference &$variable modifies the original argument.

--
The Manual | Troubleshooting FAQ | Tips for posting | How to report a security issue.

Anonymous’s picture

Thanx a lot, I appreciate your help a lot.

marenz