PHP - Function inside a Function. Good or bad? - php

I would like to know if it is a good thing to define a function inside another function in PHP. Isn't it better to define it before the function (and not inside) in terms of performances.

I think you should care more about maintenability, and less about performance, especially in that kind of situation, where the difference in performances is probably not that big between the two solutions, while the difference in maintenability seems important.
Like Donald Knuth said :
We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil.
This is quite true, in this situation ;-)

There are multiple reasons against it:
The documentation of the inner function will not be parsed.
The inner function only exists after the outer function has been called (but even outside the scope of the outer function afterwards)
It is hard to read (because it is not seen commonly)
The only advantage I could think of is defining a callback, but this is better done with create_function() (<PHP 5.3) or closures (>=PHP5.3)
If you're concerned about performance on this level, you should really be using another language

It depends on the situation, as it may be more desirable than using create_function(). However you should know that the function which is created within the function is global in scope.
function creator() {
function inside() {
echo "hi.";
}
}
creator();
inside();
This will print "hi." even though the inside() function was created "inside" of the creator function. So if you have a function in a loop which is creating a function, you need to check to see if the function exists, otherwise it will cause a function exists error after the first loop.

That's a bad practice. Not only all weird things can happen and you'll lose too much time trying to debug it, but also the code becomes more confusing.
In terms of performance I'm not completely sure about it. All I know is that if you define a function inside another, that last function will only exist if the outer one is called. That may relief some memory. But I believe the payoff is not significant.
A very common way is to define the function outside of that function and call it inside.

Related

Passing globals thru function arguments

1I know it may sound silly from the get go...
and let me tell you right off the batt, this ain't the same question as The advantage / disadvantage between global variables and function parameters in PHP. asked right here on stackoverflow. There, asker wonders local vars vs global vars. Here, globals vs globals. My question is all about the PHP's internal way of handling the global variable access and speed.
Here is the question, in the below examples, is the function_1 supposed to run faster than the function_2?
function function_1 ( &$global_variable_x) {
//do something with $global_variable_x
}
function function_2 () {
global $global_variable_x;
//do something with $global_variable_x
}
Let me highlight what's the difference...
In case 1, you pass the global in the function arguments and not only that, you pass it as by ref so the memory location is handed to PHP directly. Because of this trick, there is no need for the use of the global keyword within the function, and because of this very fact, there is no time spent by PHP looking up the global in the global name space. Then the question is why not do it? It's got to be faster, ain't it?
Of course, it is easy to misinterpret this question and get into the usual chores of talking about
Globals are bad
Globals do not need to be passed thru function args because globals well... are globals, so they can be accessed anywhere anyway.
and finally, it does not make sense to pass a global thru a function argument from a semantical point of view, it confuses the hell out of people.
none of which addresses the question being asked.
It's all about speed.
if its global it makes no sense to use it as an argument to a function which can see that global. It either 1) won't be faster or 2) it will run barely slower 3) it will run faster by very little and the reason for this will defy formal logic.

PHP 101: variable vs function

I'm creating a global file to hold items that will be re-used throughout my website. What are the differences between these two lines of code? Is one "better" than the other?
This:
$logo = "img/mainlogo.jpg";
vs this:
function logo() {
echo "img/mainlogo.jpg";
}
You should code clear and readable and split in the html and php. The performance profit is not significant...
<?php
...
$logo = "img/mainlogo.jpg";
...
?>
...
<img src="<?= $logo ?>" alt="logo">
...
Of the two options you posted, the function is the better choice. But, to be brutally honest, this sort of thing is exactly what constants are for:
defined('MAIN_LOGO') || define('MAIN_LOGO','img/mainlogo.jpg');
suppose you're working on a site that has to support multiple languages, then you can simply use the same trick:
defined('CLIENT_LOCALE') || define('CLIENT_LOCATE',$whereverYouGetThisFrom);
defined('MAIN_LOGO') || define('MAIN_LOGO','img/mainlogo_'.CLIENT_LOCALE.'.jpg');
//if language is EN, mainlogo_EN.jpg will be used, if lang is ES, mainlogo_ES.jpg, etc...
Besides, a constant, once defined cannot be redefined (clue is in the name, of course). Also: since PHP still has a lot of C-stuff going under the bonnet, and you've tagged this question performance, it might interest you that constants are much like C's macro's, which are a lot faster than regular function calls, or even C++ inline functions (even if they were indeed compiled as inline functions).
Anyway, if you have a ton of these things you want to centralize, either think of creating a couple of ini files for your project, and parse them into some sort of global object
Functions are good.
I see that function logo() is better than $logo. echo doesn't take much memory, but $logo does. Even though, function logo() takes something, it will be handled by PHP's very own garbage collector. You can also use these functions to ensure that you are not misusing the memory allocated.
memory_get_peak_usage();
memory_get_usage();
Explanation:
Upon the ending of an in use function PHP clears the memory it was using, at least more efficiently than if not using a function. If you are using recursive code or something similar that is memory intensive try putting the code into a function or method, upon closing of the function/method the memory used for the function will be garbaged much more efficiently than that of unsetting variables within the loop itself.
Source: 7 tips to prevent PHP running out of memory
The main purpose of a function is to avoid code repetition and perform a specific task. Based on that definition, using a function to only return a value is a bad design.
In that context I think is better a good readability in the code than to save several bytes of memory. We are in 2012, optimization is good but this type of micro-optimization is simply ridiculous. I prefer assigning a variable, it's clear and do what you expect.
$logo = "img/mainlogo.jpg"; can be redefined naturally later without changing code by doing this $logo="img/newmainlogo.jpg"; whereas the function would have to be modified itself, in its first definition.

Which is the better way to reference a variable outside the function scope?

I can change $var in my function in one of two ways: either pass it by reference or using the global keyword.
$var1 = 10;
function test1() {
global $var1;
$var1++;
}
function test2(&$var) {
$var++;
}
Both approaches have the same result, but is there any difference between them? Which one is preferred and which one is faster?
1. None of them is preferred.
Unless you have a special reason to do otherwise, the preferred would be
$var1 = 10;
$var1 = test3($var1);
function test3($var)
{
return $var + 1;
}
Introducing coupling between different parts of your program (if using a global) is something you should always reasonably try to avoid.
In addition, if there is no concrete reason to make your function accept its argument by reference you should also avoid doing that. Only a very miniscule fraction of all functions behave this way, so if nothing else you are risking confusion among the developers who use this code for no real benefit.
2. You do not need to think about which one is faster.
Unless you have profiled your application under real world scenarios and have found that this function is a bottleneck (which of course it will never be in this simple form), then optimizing for performance at the expense of writing clear and maintainable code is not only pointless, but also detrimental.
As a bonus, I should mention that using a reference might actually make the function slower.
Since global variables pollute the namespace (i.e. can be used inadvertently and/or by another function with the same idea), references are preferable.
However, in many cases (where the data structures are more complex), you should be using objects instead, like this:
class Counter {
private $val = 10;
public function increment() {
$this->val++;
}
}
The speed of any of these solutions does not matter and will be dwarfed by any actual computation.
Preferred way is avoiding globals. The reason is that if you put a variable in global scope, you lose control over it - since projects grow, you might forget what the name of your global variable is and you can overwrite it accidentally somewhere causing an incredible headache for yourself.
From performance point of view - reference is faster and it's also much safer to use because you define in method's signature whether a reference is being used or not, making the actual function call easy as you don't have to pass the variable by reference explicitly.

The advantage / disadvantage between global variables and function parameters in PHP?

sorry i'm a beginner and i can't determine how good a question this is, maybe it sounds utterly obvious to some of you.
if our use of these two below is the same which is better?
function doSomething ($var1,$var2,..){
...
}
OR
function doSomething (){
global $var1,$var2,..;
...
}
by our use I mean that I know that in the second scenario we can also alter the global variables' value. but what if we don't need to do that, which is the better way of writing this function? does passing variables take less memory than announcing global's in a function?
The memory usage is a paltry concern. It's much more important that the code be easy to follow and not have... unpredicted... results. Adding global variables is a VERY BAD IDEA from this standpoint, IMO.
If you're concerned about memory usage, the thing to do is
function doSomething (&$var1, &$var2,..) {
...
}
This will pass the variables by reference and not create new copies of them in memory. If you modify them during the execution of the function, those modifications will be reflected when execution returns to the caller.
However, please note that it's very unusual for even this to be necessary for memory reasons. The usual reason to use by-reference is for the reason I listed above (modifying them for the caller). The way to go is almost always the simple
function doSomething ($var1, $var2) {
...
}
Avoid using global variables, use the passing variables in parameters approach instead. Depending on the size of your program, the performance may be negligible.
But if you are concerned with performance here are some key things to note about global variable performance with regards to local variables (variables defined within functions.)
Incrementing a global variable is 2 times slow than a local var.
Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
Also, global variables increase the risk of using wrong values, if they were altered elsewhere inside your code.
Write it to take parameters. Maintainability is far more important than micro-optimization. When you take parameters, the variables can not be modified in unexpected places.
Although it is not good practice as long as you guarantee that the global is never written, but only read you will have the flexibility of paramaters.
As as alternative, you can pass one parameter (or two if it really goes with the function, like exp) and the rest in an array of option (a bit like jquery does).
This way you are not using globals, have some parameter flexibility and have clearly defined the defaults for each parameter.
function get_things($thing_name,$opt= array() {
if(!isset($opt["order"])) $opt["order"]= 'ASC';
}
Pass in parameters, avoid globals. Keeping only the scope you need for a given situation is a measure of good code design. You may want to look at PHP variable scope...
http://php.net/manual/en/language.variables.scope.php
An excellent resource, with some pointers on what is best practices and memory management.
As of PHP 4 using global with big variables affects performance significantly.
Having in $data a 3Mb string with binary map data and running 10k tests if the bit is 0 or 1 for different global usage gives the following time results:
function getBit($pos) {
global $data;
$posByte = floor($pos/8);
...
}
t5 bit open: 0.05495s, seek: 5.04544s, all: 5.10039s
function getBit($data) {
global $_bin_point;
$pos = $_bin_point;
$posByte = floor($pos/8);
}
t5 bit open: 0.03947s, seek: 0.12345s, all: 0.16292s
function getBit($data, $pos) {
$posByte = floor($pos/8);
...
}
t5 bit open: 0.05179s, seek: 0.08856s, all: 0.14035s
So, passing parameters is way faster than using global on variables >= 3Mb. Haven't tested with passing a $&data reference and haven't tested with PHP5.

Proper way to declare a function in PHP?

I am not really clear about declaring functions in php, so I will give this a try.
getselection();
function getselection($selection,$price)
{
global $getprice;
switch($selection)
{
case1: case 1:
echo "You chose lemondew <br />";
$price=$getprice['lemondew'].'<br>';
echo "The price:".$price;
break;
Please let me know if I am doing this wrong, I want to do this the correct way; in addition, php.net has examples but they are kind of complex for a newb, I guess when I become proficient I will start using their documentation, thank you for not flaming.
Please provide links that might also help me clear this up?
Your example seems valid enough to me.
foo('bar');
function foo($myVar)
{
echo $myVar
}
// Output: bar
See this link for more info on user-defined functions.
You got off to a reasonable start. Now all you need to do is remove the redundant case 1:, close your switch statement with a } and then close your function with another }. I assume the global array $getprice is defined in your code but not shown in the question.
it's good practice to declare functions before calling them. It'll prevent infrequent misbehavior from your code.
The sample is basically a valid function definition (meaning it runs, except for what Asaph mentions about closing braces), but doesn't follow best practices.
Naming conventions: When a name consists of two or more words, use camelCase or underscores_to_delineate_words. Which one you use isn't important, so long as you're consistent. See also Alex's question about PHP naming conventions.
Picking a good name: a "get" prefix denotes a "getter" or "accessor"; any method or function of the form "getThing" should return a thing and have no affects visible outside the function or object. The sample function might be better called "printSelection" or "printItem", since it prints the name and price of the item that was selected.
Globals: Generally speaking, globals cause problems. One alternative is to use classes or objects: make the variable a static member of a class or an instance member of an object. Another alternative is to pass the data as an additional parameter to the function, though a function with too many parameters isn't very readable.
Switches are very useful, but not always the best choice. In the sample, $selection could easily hold the name of an item rather than a number. This points to one alternative to using switches: use an index into an array (which, incidentally, is how it's done in Python). If the cases have the same code but vary in values used, arrays are the way to go. If you're using objects, then polymorphism is the way to go--but that's a topic unto itself.
The $price parameter appears to serve no purpose. If you want your function to return the price, use a return statement.
When you called the function, you neglected to pass any arguments. This will result in warnings and notices, but will run.

Categories