When Writing a Function


function pullUser($id) {

	dbconnect();
	$query = "SELECT username FROM users WHERE id = '$id'";
	$result = mysql_query($query);
	$row = mysql_fetch_row($result);
	$username = $row[0];

	return $username;

}

My question, should I use “echo” or “return” at the end? What is the difference in the end result?

I would generally say it’s better to return. That way you can use the data however you want.

The difference lies in what you want to do with the result, and where.

a) If your function echoes a result it means you have to then put that call in exactly the right place.


echo "<p>Welcome ". pullUser(23) . "</p>";

b) Returning data means you can assign the result of pullUser() to a variable and act upon it later


$name = pullUser(23);

// later, or in a template, say:

echo "<p>Welcome $name</p>";

Perhaps more pertinently though, what if you want to bring more that one value from your users table? say : username and town and then want to do some analysis - you are better returning data, and making the decision about when to display it until just prior to displaying it, in general.

In design terms you are giving pullUser() too much responsibility, if you name things by what they actually do you are in fact using pullUser() to do something very explicit.


echoUsernameById();

These might well seem minor things to you at the moment, but you cannot start thinking about them early enough, in my book.

Yeah , but this isnt the “right place”

echo "<p>Welcome ". pullUser(23) . "</p>";

Here is an example : http://codepad.viper-7.com/hUuMbr

Azazul - That’s correct;
If the function echoed directly, you would have to do


echo "<p>Welcome, ";
pullUser(23);
echo "</p>";

If however, pullUser returned the result instead of echoing it itself,

 
echo "<p>Welcome, ".pullUser(23)."</p>";

would work as intended.

Quite right, my mistake, sorry.

echo "<p>Welcome, ";
pullUser(23);
echo "</p>";

I’ve had to do this a couple times in my code, and now I understand why :slight_smile:

Thank you for all your input on this subject.