I understand I can define a function like this:
<?php
function say_hello() {
echo "hello world!";
}
say_hello();
?>
...and then reuse this function elsewhere as many times as I need by just calling the function by name.
What I don't understand is "passing data to arguments within the function". I'm confused what's meant by within.
From one of the lessons I've been studying, I have this function:
<?php
function say_helloTWO( $word ) {
echo " {$word} hello world a second time ";
}
say_helloTWO( "my name is mike");
?>
This prints on screen
my name is mike hello world a second time
When I test the function with the argument "my name is mike", it prints to screen, but I don't understand how this works. The variable $word wasn't declared anywhere, so, if I take out the "$word" from the echo, then only "hello world a second time" shows without the my name is mike.
This leads me to believe that somewhere within this block of code, $word was defined, is that right?
In your second function $word is being declared in the function definition function say_helloTWO( $word ).
So the function is expecting 1 parameter, which will be assigned to the variable $word for use within that function.
So when you call say_helloTWO( "my name is mike"); you are passing 1 parameter ("my name is mike") to the function say_helloTWO. This 1 parameter gets assigned to the 1st variable in the function definition, and is therefore available within the function as $word.
Make sense?
In this case the function definition is said to take one arguments.
function say_helloTWO( $word ) // $word is the name of this argument
When you call the function in your code the first thing you pass in the brackets will be passed as the first argument. Therefore in your example the string "my name is mike" is being passed into the function and assigned to the variable $word.
If we expand on this and have a function that takes two arguments like this
function say_helloTHREE( $word, $secondArg )
Then this function would now expect two arguments to be passed into it. The first argument would be assigned to $word and the second argument will be assigned to $secondArg.
You need to read this: http://php.net/manual/en/functions.arguments.php
<?php
function say_helloTWO( $word ) {
echo " {$word} hello world a second time ";
}
say_helloTWO( "my name is mike");
?>
In this code, the 'declaration' of the variable $word is made within the function declaration. As you see on this line function say_helloTWO( $word ) { you can find $word on that line. This is enough for the PHP parser to know that for the first agument of the is to be known as word within this functions scope. The function then echos out that variable on a later line echo " {$word} hello world a second time "; where again $word is present prints out both what you set as the value of the first argument on this line say_helloTWO( "my name is mike");.
Good question.
This counts as a valid declaration. It's defined when supplied as an argument when the function is called.
<?php
function my_name_is ($name) {
echo "Hello, my name is " . $name;
}
my_name_is('mike');
// returns 'Hello, my name is mike'
?>
Because, when calling the function, they supply 'mike' as an argument, $name becomes 'mike'. It's just how functions work.
EDIT:
It's a special rule. $name doesn't need to be declared because it will be defined when the function is called. PHP understands this. If you don't supply an argument, it's still defined, it's just empty... I believe.
It's passed as a parameter. So it was sorta already declared inside the parenthesis
If you did:
function say_helloTWO( $word1, $word2, $word3 )
and called:
say_helloTWO("a", "b", "c");
That would call say_helloTWO and set the variable $word1 to "a", $word2 to "b" and $word3 to "c"
Those three variables are defined in say_helloTWO for the duration that that function is running.
To give a practical example, say you had a function to solve quadratic equations, it would look like
function quadratic( $a, $b, $c ) {
$x = ( $b + sqrt( (b*b - 4*a*c) ) )/ 2*a;
return $x;
}
Then, instead of rewriting the code to solve a quadratic each time, you could call it like this:
$y = quadratic (1, 2, 3);
This would set $a to 1, $b to 2 and $c to 3, and store the result in $y.
You can consider the quadratic function to be a sort of "mini-program", independent of the rest of your program, $a, $b and $c only apply within the quadratic function.
this leads me to believe that somewhere within this block of code, $word was defined, is that right?
No, $word is not defined within the function block, it is given the value of "my name is mike" when you mane the call.
In other words, $word is defined when you call the function:
/* here you are defining word to "my name is mike" */
say_helloTWO( "my name is mike");
/* here you are defining word to "my name is jack"*/
say_helloTWO( "my name is jack");
If the above still don't make much sense to you then I think you may need to go back to the basic and study what is a function in programming world.
Related
These function statements are confusing me.
I'm new to php, help me to understand these functions:
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
first echo outputs 10
Second echo outputs 16
What is the difference between these 2 functions?
There are two types of call:
1) Call by value: addFive($num)
2) Call by reference: addSix(&$num)
In first case, you are just passing value of the variable.
Hence, only value gets modified keeping original variable untouched.
In second case, you are passing reference to the variable, hence the original value gets modified.
The first function passes the argument by value - in other words, it's copied into the function, and any change you perform on it will be on the local copy.
The second function passes the argument by reference (note the & before it in the function's signature). This means the variable itself is passed, and any modification you perform on it will survive beyond the function's scope.
& is used to pass address of an variable in second function declaration "addSix(&$num) {}"
In second function while calling addSix( $orignum ); updation of value is done on address of "$orignum"
whereas in first function updation is done on "$num"
First function add 5 to your number and second adds 6 to your number
$num+=6 means $num= $num+6
And first function works on Call by value and second function works on Call by reference
What does this line mean?
if ( ${fun("str1")} (fun("str2"), ${fun("str3")}) )
Evaluate function returning_value_for_str1_of_fun()_name with the parameters return value for str2 and variable with name return_value_for_str3 ?
This tests the return value of the function, whose name is the value in the variable named fun("str1"), and given the arguments fun("str2") and the value of the variable named fun("str3").
Example:
If fun("str1") equals "x", fun("str2") equals 34, and fun("str3") equals "y", then the statement would look like:
if ( $x (34, $y) )
fun("str1") returns string that should be name of variable and the value of this variable is anonymous function (that probably is not void and returns boolean) that gets two arguments first is return value fun("str2") and the second is the value of the variable with the name that matches string returned by fun("str3").
Wow. That's convoluted code. Let's examine it bit by bit:
Let's start with this:
fun("str1")
In fact, this is simply a function call to a function named fun(), passing in a string value as a parameter.
This function call is repeated three times in your code, with different strings as the arguments. The function fun() itself is not supplied in your example code, so I can't tell what it does, but given the context I assume it returns a string.
Which leads us onto the next bit we can examine:
${fun("str1")}
The ${...} syntax in PHP takes the contents of the braces and references a variable of that name.
So, for example, ${"myvar"} is the same as saying $myvar. This is called a dynamic variable name. While it does have its uses, it is a very easy way to write bad code, that is difficult to read, understand or maintain. Your example definitely falls into this category.
However, now that we understand the syntax, it's easy to see that it is taking the string output of the fun() function call, and turning it into a variable name.
Expanding further, we can rewrite the code as follows to make it clearer:
$var1 = fun("str1");
$var2 = fun("str2");
$var3 = fun("str3");
if ( $$var1 ($var2, $$var3) )
Here, $$var1 is being used as a function name, called with $var2 and $$var3 as parameters.
So in $var1, we have a function call returning a string that is being referenced as a variable name, which is being called as a function.
We still don't know what fun() function returns, or whether the variable names that are generated by its return are valid, but we can make some assumptions, as $var1 and $var2 would need to be populated with valid function names in order for your line of code to work at all.
We now have an understanding of the whole line of code, but still not a clear view of what it's trying to acheive (beyond being excessively 'clever' and obtuse).
This is very very poorly written code. It is deliberately obscure, and inefficient (ie it will run slowly).
Some work around:
$func = 'fun';
$str3 = 'str3';
echo ${fun("str1")} (fun("str2"), ${fun("str3")}); // will output 'str2'
function fun($param1, $param2 = ''){
if($param1 == 'str2' || $param1 == 'str3')
return $param1;
elseif($param1 == 'str1')
return 'func';
else
echo ' you are done';
}
Evaluates as follows:
fun("str1") -> 'func'
${fun("str1")} -> $func -> fun
fun("str2") -> 'str2'
fun("str3") -> 'str3'
${fun("str3")} -> $str3
${fun("str1")} (fun("str2"), ${fun("str3")})
=> $func ("str2", $str3)
=> fun("str2", "str3")
=> "str2"
(1) I want to know what is the difference between call by value and call by reference in php. PHP works on call by value or call by reference?
(2) And also i want to know that do you mean by $$ sign in php
For example:-
$a = 'name';
$$a = "Paul";
echo $name;
output is Paul
As above example what do u mean by $$ on PHP.
$$a = b; in PHP means "take the value of $a, and set the variable whose name is that value to equal b".
In other words:
$foo = "bar";
$$foo = "baz";
echo $bar; // outputs 'baz'
But yeah, take a look at the PHP symbol reference.
As for call by value/reference - the primary difference between the two is whether or not you're able to modify the original items that were used to call the function. See:
function increment_value($y) {
$y++;
echo $y;
}
function increment_reference(&$y) {
$y++;
echo $y;
}
$x = 1;
increment_value($x); // prints '2'
echo $x; // prints '1'
increment_reference($x); // prints '2'
echo $x; // prints '2'
Notice how the value of $x isn't changed by increment_value(), but is changed by increment_reference().
As demonstrated here, whether call-by-value or call-by-reference is used depends on the definition of the function being called; the default when declaring your own functions is call-by-value (but you can specify call-by-reference via the & sigil).
Let's define a function:
function f($a) {
$a++;
echo "inside function: " . $a;
}
Now let's try calling it by value(normally we do this):
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 1
Now let's re-define the function to pass variable by reference:
function f(&$a) {
$a++;
echo "inside function: " . $a;
}
and calling it again.
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 2
You can pass a variable by reference to a function so the function can modify the variable.
More info here.
Call by value: Passing the variable value directly and it will not affect any global variable.
Call by reference: Passing the address of a variable and it will affect the variable.
It means $($a), so its the same as $name (Since $a = 'name'). More explanation here What does $$ (dollar dollar or double dollar) mean in PHP?
Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.
Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.
I'm 'dissecting' PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:
function preparse_tags($text, &$errors, $is_signature = false)
What does the & in front of the $error variable mean?
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
It does pass by reference rather than pass by value.
This allows for the function to change variables outside of its own scope, in the scope of the calling function.
For instance:
function addOne( &$val ) {
$val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.
In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.
It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.
I know this is not exactly reflection, but kind of.
I want to make a debug function that gets a variable and prints a var_dump and the variable name.
Of course, when the programmer writes a call to the function, they already know the variable's name, so they could write something like:
debug( $myvar, 'myvar' );
But I want it to be quick and easy to write, just the function name, the variable, and voilĂ !
debug( $myvar ); // quicker and easier :)
You can do it by converting the variable to a key/value set before passing it to the function.
function varName($theVar) {
$variableName = key($theVar);
$variableValue = $theVar[$variableName];
echo ('The name of the variable used in the function call was '.$variableName.'<br />');
echo ('The value of the variable used in the function call was '.$variableValue.'<br />');
}
$myVar = 'abc';
varName(compact('myVar'));
Though I don't recommend creating a reference to a nameless variable, function varName(&$theVar) works too.
Since compact() takes the variable name as a string rather than the actual variable, iterating over a list of variable names should be easy.
As to why you would want to do this -- don't ask me but it seems like a lot of people ask the question so here's my solution.
I know I'm answering a 4 year old question but what the hell...
compact() might help you is your friend here!
I made a similar function to quickly dump out info on a few chosen variables into a log for debugging errors and it goes something like this:
function vlog() {
$args = func_get_args();
foreach ($args as $arg) {
global ${$arg};
}
return json_encode(compact($args));
}
I found JSON to be the cleanest and most readable form for these dumps for my logs but you could also use something like print_r() or var_export().
This is how I use it:
$foo = 'Elvis';
$bar = 42;
$obj = new SomeFancyObject();
log('Something went wrong! vars='.vlog('foo', 'bar', 'obj'));
And this would print out like this to the logs:
Something went wrong! vars={"foo":"Elvis","bar":42,"obj":{"nestedProperty1":1, "nestedProperty2":"etc."}}
Word of warning though: This will only work for variables declared in the global scope (so not inside functions or classes. In there you need to evoke compact() directly so it has access to that scope, but that's not really that big of a deal since this vlog() is basically just a shortcut for json_encode(compact('foo', 'bar', 'obj')), saving me 16 keystrokes each time I need it.
Nope, not possible. Sorry.
Not elegantly... BUT YOU COULD FAKE IT!
1) Drink enough to convince yourself this is a good idea (it'll take a lot)
2) Replace all your variables with variable variables:
$a = 10
//becomes
$a = '0a';
$$a = 10;
3) Reference $$a in all your code.
4) When you need to print the variable, print $a and strip out the leading 0.
Addendum: Only do this if you are
Never showing this code to anyone
Never need to change or maintain this code
Are crazy
Not doing this for a job
Look, just never do this, it is a joke
I know this is very very late, but i did it in a different way.
It might honestly be a bit bad for performance, but since it's for debugging it shouldn't be a problem.
I read the file where the function is called, on the line it was called and I cut out the variable name.
function dump($str){
// Get the caller with debug backtrace
$bt = debug_backtrace();
$caller = array_shift($bt);
// Put the file where the function was called in an array, split by lines
$readFileStr = file($caller['file']);
// Read the specific line where the function was called
$lineStr = $readFileStr[$caller['line'] -1];
// Get the variable name (including $) by taking the string between '(' and ')'
$regularOutput = preg_match('/\((.*?)\)/', $lineStr, $output);
$variableName = $output[1];
// echo the var name and in which file and line it was called
echo "var: " . $variableName . " dumped in file: " . $caller['file'] . ' on line: ' . $caller['line'] . '<br>';
// dump the given variable
echo '<pre>' . var_export($str, true) . '</pre>';
}
i've had the same thought before, but if you really think about it, you'll see why this is impossible... presumably your debug function will defined like this: function debug($someVar) { } and there's no way for it to know the original variable was called $myvar.
The absolute best you could do would be to look at something like get_defined_vars() or $_GLOBALS (if it were a global for some reason) and loop through that to find something which matches the value of your variable. This is a very hacky and not very reliable method though. Your original method is the most efficient way.
No, the closer you will get is with get_defined_vars().
EDIT: I was wrong, after reading the user comments on get_defined_vars() it's possible with a little hack:
function ev($variable){
foreach($GLOBALS as $key => $value){
if($variable===$value){
echo '<p>$'.$key.' - '.$value.'</p>';
}
}
}
$lol = 123;
ev($lol); // $lol - 123
Only works for unique variable contents though.
Bit late to the game here, but Mach 13 has an interesting solution: How to get a variable name as a string in PHP
You could use eval:
function debug($variablename)
{
echo ($variablename . ":<br/>");
eval("global $". $variablename . ";");
eval("var_dump($" . $variablename . ");");
}
Usage: debug("myvar") not debug($myvar)
This is late post but I think it is possible now using compact method
so the code would be
$a=1;
$b=2;
$c=3
var_dump(compact('a','b','c'));
the output would be
array (size=3)
'a' => int 1
'b' => int 2
'c' => int 3
where variable name a, b and c are the key
Hope this helps
I believe Alix and nickf are suggesting this:
function debug($variablename)
{
echo ($variablename . ":<br/>");
global $$variablename; // enable scope
var_dump($$variablename);
}
I have tested it and it seems to work just as well as Wagger's code (Thanks Wagger: I have tried so many times to write this and the global variable declaration was my stumbling block)