Confusion about returning in custom function

I have few questions regarding the return statement.

a) it is mandatory to define a return statement in a user-defined function.?

b), does it remain valid if I just define a return statement without any parameter? will it return a null value?

c) there is the following function:

function admin_credential($password = 0, $email = 0) { if( $password != 0) { $password = sha1($password); $query = "UPDATE admins SET password = '$password'"; $result = mysql_query($query); } if( $email != 0) { $query = "UPDATE admins SET email = '$email'"; $result = mysql_query($query); } return; } 
+4
source share
4 answers

a) it is mandatory to define a return statement in a user-defined function.?

Not.

b), does it remain valid if I just define a return statement without any parameter? will it return a null value?

Yes.

c) there is the following function:

Yes, but $result will be lost because you are not returning it. return not required.

+3
source

a) you do not need to return a value at the end of a function in PHP. This is roughly equivalent to the C void function.

b) a return doesn't matter, but it can be confusing for other people who look at your code later, so it's a bad idea to do this standard practice. Consider instead returning NULL , which will have the same effect.

c) Yes, your function uses the correct syntax.

+2
source

a) it is mandatory to define a return statement in a user-defined function.?

Not. Sometimes you write functions that return nothing to the called function, say, a function to print a multidimensional array is pretty nice.

b), does it remain valid if I just define a return statement without any parameter? will it return a null value?

Yes. Omitting return same as return without any parameters, and both return NULL .

c) there is the following function:

Syntactically correct. But it would be more meaningful if you return a boolean to indicate the success / failure of the request. In order for the caller to know that the database update was normal or not.

EDIT:

 "UPDATE admins SET password = '$password'" 

The request is missing a WHERE . Therefore, it effectively updates the password of all users in the admins table.

+2
source

When you look at PHP tables for user authentication, there are many things to consider. You need to talk about how you want to store data in your tables and how to get it. This means that you need to consider how many users will have access and how many user types. If you have multiple users, for example, less than 10, I recommend not to worry about authenticating database users.

You asked the questions you answered, but I urge you to try to avoid a complex system with many unnecessary features: simplicity.

+1
source

All Articles