First of all, I can't recall the name of this process, but it looks something like this:
function test($alter = FALSE){
//do stuff
return $alter;
}
Making $alter = FALSE right in the function declaration
What is that called? How does this work? What happens in the following circumstances?
$result = test();
$result = test(TRUE);
FALSE is defined as the default value if no other value is passed.
In the case of you examples the results (in order) would be:
FALSE
TRUE
FALSE defined in method header is the default value (if nothing is added to parameter while calling) - test() otherwise it behaves like a normal parameter.. so if you call test(TRUE) value will be TRUE
Nothing to add except: The term that you probably might be remembering is "function overloading" but this isn't a real embodiment of this (it's just PHP's "default parameter" is perhaps similar)
"<?php
echo"welcome";
function a($b=false){
echo"<br /> b: ".$b;
}
a(true);
a();
a("some text");
a(false);
?>
result :
welcome
b: 1
b:
b: some text
b:
"
it seems that if its false/null/empty it does not print anything..
and what ever you pass to that method string/boolean it does print as long as not null/empty.
Related
I am confused about return statement , why we need to use return in end of function , for example
function test($a){blah;
blahh ;
blahhh;
blahhhhh;
return;}
What the use of return here? Function automatically terminates when all the statements executed , I think there is no use of return here , but this picture from http://www.w3resource.com/php/statement/return.php make me confused
So
Can someone please explain the use of return (when we not returning any value).
It depends on what you're trying to achieve.
If you write echo in several places, your code will get confusing. In general, a function that returns a value is also more versatile, since the caller can decide whether to further manipulate that value or immediately print it.
I'd recommend to stick to the convention and use return for a function.
You should check GuardClause.
Example:
function test() {
return 10;
}
$a = test(); // $a stores the value 10
echo $a; // Prints 10
echo $a + 5; // We may want to manipulate the value returned by the function. So, it prints 15.
For further reference, check What is the difference between PHP echo and PHP return in plain English?
In that context: You don't.
return breaks out of the function, but since it is the last statement in that function, you would break out of it anyway without the statement.
return passes its argument back to the caller, but since it doesn't have an argument, there is nothing to pass.
So it does nothing.
Don't assume that every piece of code you stumble across has a purpuse. It might be left over from an earlier version of the code where something else (which gave it meaning) has been removed. It might be written by someone cargo culting. It might be placeholder for future development.
"return" is important when you plan to call this function from other codes, it helps you to:
Know if the function works correctly, or not.
Obtain values from a function.
Make sure other codes are not executed after return.
It might be useless when the code is simple as your sample, let's make it more complex.
function test($a){
if(file_exists($a)){
if(is_file($a)){
return $a." IS A FILE\n";
} else if(is_dir($a)) {
return $a." IS A DIR\n";
} else {
return $a." EXISTS, BUT I DONT KNOW WHAT IT IS\n"
}
} else {
return $a." NOT EXISTS\n";
}
return 0;
}
$filecheck = test("/abc/def.txt");
if($filecheck){
echo $filecheck;
} else {
echo "unknown error";
}
Above shows how to return a value, and do some basic handling.
It is always good to implement return in your functions so you can even specify error code for your functions for reference.
Based on your example, I'll modify slightly like below:
function test($a){
blah;
blahh;
blahhh;
blahhhhh;
return 1;
}
So I know the code is running to last line.
Otherwise the function just finishes silently.
It's useful if you want a function to return a value.
i.e.
Function FavouritePie($who) {
switch($who) {
case 'John':
return 'apple';
case 'Peter':
return 'Rhubarb';
}
}
So, considering the following:
$WhatPie = FavouritePie('John');
echo $WhatPie;
would give
apple
In a really simple form, it's useful if you want a function to return something, i.e. process it and pass something back. Without a return, you'd just be performing a function with a dead end.
Some further reading:
http://php.net/manual/en/function.return.php
http://php.net/manual/en/functions.returning-values.php
To add some further context specific to the answer, if the question boils down to "Do I need to add a return for the sake of it, at the end of a function, then the answer is no. But that doesn't mean the correct answer is always to leave out your return.
it depends what you want to do with $a.
If you echo $a within the function, that function will spit out $a as soon as it is called. If you return $a, assuming you set the calling of test to a variable (i.e. $something = $test('foo')), then you can use it later on.
We got a PHP file in school with some functions and one of them is the following:
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
My question: What does the $afields=null and $avalues=null mean?
Thank you!
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
It means that, when you call your function and don't pass those parameters then it'll by default place value as null
Example :
function hello($name = "anonymous"){
return "Hello $name \n";
}
echo hello();//Hello anonymous
echo hello("BigSeeProduction");//Hello BigSeeProduction
DOCS
These assignments are default values. If you were to call the function as e.g.
serviceRec($a, $b)
the omitted parameters would be assumed to be null. If, on the other hand, you called the function as e.g.
serviceRec($a, $b, $c, $d)
$afields would be set to $c and $avalues to $d.
Of course, you could also call with 3 parameters.
It Means it's the default value. So when u don't fill this parameter it will be set as null.
See the man here :
PHP.net : default value function
That indicates, that if you leave that parameter out(Don't specify it at all), the value after the =, in this case null is used. So if you don't care about these parameters just leave them out. It has the same effect as just supllying null.
Why some programmer set null in function arguments ?
like:
function func ($arg1, arg2 = null)
{
print $arg1.' '.$arg2;
}
So I can call it with this: func('test1') (without wrote $arg2) it print test1 but if call func('test1','test2')... it only print test1.
Also speed of run and debug function is very important for me...also all functions are static...I must bring function under a class or without class is more fast? I am not care about object oriented ...only speed.
There is a nice trick to emulate variables/function calls/etc as default values:
<?php
$myVar = "Using a variable as a default value!";
function myFunction($myArgument=null) {
if($myArgument===null)
$myArgument = $GLOBALS["myVar"];
echo $myArgument;
}
// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
?>
In general, you define the default value as null (or whatever constant you like), and then check for that value at the start of the function, computing the actual default if needed, before using the argument for actual work.
Building upon this, it's also easy to provide fallback behaviors when the argument given is not valid: simply put a default that is known to be invalid in the prototype, and then check for general validity instead of a specific value: if the argument is not valid (either not given, so the default is used, or an invalid value was given), the function computes a (valid) default to use.
Incorrect usage of default function arguments
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // won't work as expected
?>
The above example will output:
Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .
Now, compare the above with this:
Correct usage of default function arguments
<?php
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // works as expected
?>
The above example will output:
Making a bowl of acidophilus raspberry.
Note: As of PHP 5, arguments that are passed by reference may have a default value.
Here are few links I am adding for you to learn function arguments in depth -
http://www.w3schools.com/php/php_functions.asp
http://php.net/manual/en/functions.arguments.php
I inherited a php codebase that contains some variable assignments in function calls:
<?php
function some_func($foo, $state) {
....
}
some_func("random stuff", $state = true);
...
some_func("other stuff", $state = false);
...
?>
I did some research and some tests, but I can't find out what the defined behaviour for this code is in PHP.
How is the value of the second argument to some_func() computed? The content of the 4state variable (true on first call, false on second)? Or is it the outcome of the assignment (i.e. assigning true/false to the variable $state was successful, so some_func received true?
What is the value of the $state variable in the global scope? The result of the assignment, i.e. true after the first call, false after the second?
I too had to work with a codebase that had function calls similar to this. Luckily, I had access to developers that wrote the code. Here is what I learned.
Scenario 1:
Simply a way to document the code. You know the variable name that you are passing into the function.
Scenario 2:
Here is a link: http://www.php.net/manual/en/language.references.pass.php
If you see, they do specifically call out your case:
foo($a = 5); // Expression, not variable
A 'dummy' pass-by-ref. Depending on your version of PHP, it may throw a warning. I was getting this: Strict Standards: Only variables should be passed by reference in ...
Now let me go into detail of what is happening in this situation.
The dangerous thing is that your example that you have provided wont display the "gotcha!" behavior. In a case like this, your $arg2 that you are echoing outside of the function will always be what the expression in the function call set it to be. Furthermore, the function that is being called will also be sent a "copy" of that value, and work with that. I say "copy" because even though the function is requiring a pass-by-ref, it is actually getting a copy, similar to what a normal function parameter would get.
If you modify the $arg2 that is inside of the function it WILL NOT modify the $arg2 that is outside of the function, as you would expect from a function that is pass-by-ref.
To assign a variable at function call time, you have to pass it as a reference (&$var):
function my_function($arg1, &$arg2) {
if ($arg1 == true) {
$arg2 = true;
}
}
my_function(true, $arg2 = false);
echo $arg2;
outputs 1 (true)
my_function(false, $arg2 = false);
echo $arg2;
outputs 0 (false)
How is the value of the second argument to some_func() computed?
It's not "computed" but explicitly setup : $state = true / false and then passed as argument to some_func().
What is the value of the $state variable in the global scope?
$state does not exist in the global scope.
Example:
function example($x = "")
{
Do something
}
Isn't $x empty by default already? Why set it explicitly?
Isn't $x empty by default already?
If no default is specified, $x is not an empty string by default, but an undefined variable. There is a difference between "" and NULL or undefined.
However, setting the default allows you to omit the parameter when calling the function, without it throwing a warning.
<?php
function test1($x = "DEFAULT") {
echo $x;
}
function test2($x) {
echo $x;
}
// Call each without the parameter $x:
test1();
// DEFAULT
test2();
// Output:
PHP Warning: Missing argument 1 for test2(), called in /home/mjb/test.php on line 10 and defined in /home/user/test.php on line 5
PHP Notice: Undefined variable: x in /home/user/test.php on line 6
The main reason is that setting a default on the declaration makes the argument optional:
$a = example();
$b = example(5);
One reason is so when you reuse the function you dont have to explicitly set the variable. This happens a lot when a default is set to true or false. That way a function can seem to be overloaded like you can do in other oop languages. If that variable didn't contain a default value, you'd always have to set that value or your function would throw an error, however, by setting the variable to a default value you wouldn't have to necessarily set the value of the variable. Hope that helps some :)
Once of the reasons I use default values is so that I do not have to declare the variable when calling function ie:
function something(debug=false){
doing something here;
if ($debug === true){
echo 'SOMETHING';
}else{
return true;
}
}
This way you can debug something bu simply adding the variable to the function call but if you dont' add it the functions assumes it is false. This is valuable in my $_GET security function that I am using to encrypt my $_GET strings when I turn on debug the $_GET is decoded and dumped as an array inside a
<pre>print_r($_GET);</pre>
so that I can see what the values are in the $_GET but the string is still encrypted in the address bar.
Hope that helps