PHP - using global vs passing by reference [duplicate] - php

This question already has answers here:
Advantage of passing by reference opposed to using global?
(6 answers)
Closed 5 years ago.
Is there any practical difference between using globals and passing param by reference?
Simple example:
$my_var = 5;
$my_var2 = 3;
function add_one(&$i){
return $i++;
}
function add_one_global(){
global $my_var2;
return $my_var2++;
}
add_one($my_var);
echo "$my_var<br>";
add_one_global();
echo "$my_var2";
The output is:
6
4
Both of them modify global variable (aware that it should be avoided if possible), "add_one" seems to be a little bit more flexible, but apart from that is there any other difference?

Not really, there is no difference. What kind of difference did you expect? The only real difference is the one that you noticed yourself - the pass-by-reference is more flexible and doesn't pollute the global namespace.
If this is for a small one-off script that you need to run once and then discard, go for whichever is fastest for you.
If this is for something that will keep working for a while, pick the pass-by-reference. It will be a lot easier down the road when you need to do some modifications to the script (and that's a when, not an if).

Related

Currying in_array() in PHP [duplicate]

This question already has answers here:
Is it possible to curry method calls in PHP?
(8 answers)
Closed 5 years ago.
Don't necessarily have a problem with how PHP does this or anything, more just a question out of curiosity. I am familiar with functional programming but am by no means an expert. I am writing functions currently and although I have no requirement for them to be functional, that may change in the future. So best to be prepared I say.
My question is, how would you curry a function like in_array?
From what I understand we have two parameters, needle and haystack.
Both seem to be required when the function is called.
We must know the array we are searching at the start of the function, and we must also know what we are searching for.
To me it seems hard to force any partial application or currying solution whereby we might know one or the other at a later point.
I suppose you could have a non-generic function whereby you specify the needle within the function. I did see something about spattering in Google. How would you handle this if asked to rewrite the function and curry it? I know I specified PHP but I suppose any language is really fine as long as the specs are the same.
Well, it's relatively straightforward in PHP - almost the same as in any other language that treats functions as values. For example:
function create_search_by_array($arr) {
return function($needle) use ($arr) {
return in_array($needle, $arr);
};
}
$search_in_1_to_10 = create_search_by_array(range(1, 10));
var_dump($search_in_1_to_10(1)); // true
var_dump($search_in_1_to_10(10)); // true
var_dump($search_in_1_to_10(11)); // false
The only caveat here is use ($arr) construct: without it, the inner function won't be able to see the corresponding variable from an outer scope.

'&' sign before function name in PHP [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 8 years ago.
Can you please explain to me the differences between two functions:
function &a(){
return something;
}
and
function b(){
return something;
}
Thanks!
The first returns a reference to something, the second a copy of something.
In first case, when the caller modify the returned value, something will be modified as a global variable do.
In the second case, modifying a copy as no effect to the source.
An ampersand before a function name means the function will return a reference to a variable instead of the value.
According to this LINK
Returning by reference is useful when you want to use a function to find to which
variable a reference should be bound. Do not use return-by-reference to increase
performance. The engine will automatically optimize this on its own. Only return
references when you have a valid technical reason to do so.

PHP: why are some internal functions missing from `get_defined_functions`? [duplicate]

This question already has answers here:
What is the difference between a language construct and a "built-in" function in PHP?
(4 answers)
Closed 8 years ago.
PHP has a large number of batteries-included functions, e.g. functions on arrays. Some of these, like each, are present in get_defined_functions()['internal']. Others, like reset and many others, are not present at all. However, they are treated as functions in every other way: they are not documented as "language constructs" or keywords; I can call them using the "variable function" feature; function_exists("reset") returns true; if I try to redefine them (e.g. function reset() { ... }), I get an error about redeclaration, rather than a syntax error; and so on.
Why are these functions not listed by get_defined_functions? Are they not actually functions? If not, what are they? If they are functions, then what actually is it that get_defined_functions is listing? In either case, how do I list the things that don't appear in get_defined_functions?
Quite a short answer: Reset is present in get_defined_functions()['internal'].
Look at [1532] in this fiddle: http://phpfiddle.org/main/code/h5n-ndx

add math operators in function php [duplicate]

This question already has answers here:
How to mathematically evaluate a string like "2-1" to produce "1"?
(9 answers)
Closed 9 years ago.
I'm kinda new to this but I was wondering if it is possible to add some dynamic calculation into a function as a parameter.
The thing is inside my function I am formatting stuff in a consistent way but each time I want to add a certain different calculation into the parameter.
<?php
function dynamicCalculator($calculation){
$result = $calculation;
//some formatting
return $result;
}
echo dynamicCalculator('(3x5)+1');
This doesn't work of course but if anyone has an idea how this could work I would love to hear it.
What you are looking for is the eval function.
eval('$result = (3*5)+1');
But beware to make sure you're not passing possibly harmful code to that function.
Your looking for RPN (Reverse Polish Notation)
Here is one example
http://pear.php.net/package/Math_RPN/
which would allow you to use
$expression = "(2^3)+sin(30)-(!4)+(3/4)";
$rpn = new Math_Rpn(); echo $rpn->calculate($expression,'deg',false);
And not have to use Eval
Use eval. eval("10+2") should return 12. Be careful though, you can also run PHP code with eval.
Someone else had a similar question on StackOverflow.
You could use this:
function dynamicCalculator($calculation) {
$result = eval($calculation);
return $result;
}

One line code to get one value from function that returns an array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)
In PHP there are functions that return an array, for example:
$a = parse_url("https://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com
My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:
echo parse_url("https://stackoverflow.com/q/9461027/87015")["host"];
Note: function array dereferencing is available since PHP 5.4; the above code works as-is.
You can do a little trick instead, write a simple function
function readArr($array, $index) {
return $array[$index];
}
Then use it like this
echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");
Honestly, the best way of writing your above code is:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["scheme"];
echo $a["host"];
Isn't that what I originally posted?
Yes. Depending on context you may want a better name than $a (perhaps $url), but that is the best way to write it. Adding a function is not an attractive option because when you revisit your code or when someone reads your code, they have to find the obscure function and figure out why on earth it exists. Leave it in the native language in this case.
Alternate code:
You can, however, combine the echo statements:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a['scheme'], $a['host'];

Categories