PHP 101: variable vs function - php

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.

Related

Correct placement of functions in PHP code [duplicate]

Consider this snippet:
function f() {
return 'hi';
}
echo f();
Vs this snippet:
echo f();
function f() {
return 'hi';
}
When I run the scripts, they both produce the same results. That's great.
But my question is (and I could not find a good answer or reference in any of my searches), is it okay to call the function before it is defined (ie, from a sequential parsing of the script file perspective)?
I don't want to run into any issues or deprecation down the road if I leave the function call ahead of the function definition block in my script file.
From the Manual:
Functions need not be defined before
they are referenced, except when a
function is conditionally defined as
shown in the two examples below.
The possibility to call (reference) a function before it is defined is a PHP intentional feature and I don't think you need to worry about it becoming deprecated.
As an observation, if you can choose from declaring the function before or after, it would be common sense to declare it before it's used.
Note: The following code will give a fatal error because the function will only be defined at run rime.
<?php
echo helloWorld();
if(1){
function helloWorld() {
return 'hello world';
}
}
?>
compiler steps are like so:
Converts a sequence of characters into tokens
Analyses the tokens to determine there Grammatical structure.
Generates byte code depending on the outcome of the analyses
So the easiest way to understand this is just because the script is not multi threaded does not mean its processed in one in line execution.
PHP Reads your entire source code into tokens before its executed, there for it has control over the order of tokens should be executed first.
Take this example
while(true)
{
print '*';
}
Each line is a sequence of characters, so PHP Would interpret this as
if #T_IF
#T_WHITESPACE
(
#T_WHITESPACE
true #T_STRING
#T_WHITESPACE
)
#T_WHITESPACE
{
#T_WHITESPACE
print #T_PRINT
#T_WHITESPACE
'*'; #T_CONSTANT_ESCAPED_STRING
#T_WHITESPACE
}
but just because its been read does not mean its been executed.
So that functions are at the top of the list, this way you can execute them because there already within the systems memory.
I believe that the reason for this is that PHP's native library such as PFO,mysql_connect functions and classes are loaded first, and they move all user defined scopes to be loaded after there native implementations.
there loaded at the beginning of execution.
This is such a great question. Because it doesn't have a really good answer. PHP will, if given the chance, work just fine doing it backwards. Until it doesn't. And it won't if, for example, the function is defined in a yet-to-be loaded included file later on. PHP will include those files as they happen in code, so you will get a function not defined error in that case.
This is one SERIOUS gotcha in PHP.
It helps to imagine that includes are like copy/pasting whatever was in the other file into the code. But that it only happens when they get run in code. Which means they can be dynamic and based on the running code. But it also means they can't be pre-processed and linked up before-hand.
I find it a good practice to first define my functions and later call them, but it doesn't matters where do you put them as long they're there ;)
Also, i like to have my functions separated in different php files, depending on the use, just to be organized :)
No matter where you define your function and where you call. Because as far as I know, PHP server application first reads the whole page then executes it.

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.

PHP - Function inside a Function. Good or bad?

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.

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.

What are some useful PHP Idioms?

I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.
Some examples:
Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php
if ( count($arrayName) ) // handles $arrayName being unset or empty
Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);
Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...
Apply liberally for fun and profit:
Iterators in foreach loops. There's almost never a wrong time.
Design around class autoloading. Use spl_autoload_register(), not __autoload(). For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.
Typehint everywhere. Use assertions for scalars.
function f(SomeClass $x, array $y, $z) {
assert(is_bool($z))
}
Output something other than HTML.
header('Content-type: text/xml'); // or text/css, application/pdf, or...
Learn to use exceptions. Write an error handler that converts errors into exceptions.
Replace your define() global constants with class constants.
Replace your Unix timestamps with a proper Date class.
In long functions, unset() variables when you're done with them.
Use with guilty pleasure:
Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.
Use output buffers for assembling long strings.
ob_start();
echo "whatever\n";
debug_print_backtrace();
$s = ob_get_clean();
Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:
Magic methods (__get, __set, __call)
extract()
Structured arrays -- use an object
My experience with PHP has taught me a few things. To name a few:
Always output errors. These are the first two lines of my typical project (in development mode):
ini_set('display_errors', '1');
error_reporting(E_ALL);
Never use automagic. Stuff like autoLoad may bite you in the future.
Always require dependent classes using require_once. That way you can be sure you'll have your dependencies straight.
Use if(isset($array[$key])) instead of if($array[$key]). The second will raise a warning if the key isn't defined.
When defining variables (even with for cycles) give them verbose names ($listIndex instead of $j)
Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using Zend Framework's naming conventions because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the full backtrace.
Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.
The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.
Make liberal use of === over ==. For instance:
if (array_search('needle',$array) == false) {
// it's not there, i think...
}
will give a false negative if 'needle' is at key zero. Instead:
if (array_search('needle',$array) === false) {
// it's not there!
}
will always be accurate.
See this question: Hidden Features of PHP. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.
There are a few things I do in PHP that tend to be PHP-specific.
Assemble strings with an array.
A lot of string manipulation is expensive in PHP, so I tend to write algorithms that reduce the discrete number of string manipulations I do. The classic example is building a string with a loop. Start with an array(), instead, and do array concatenation in the loop. Then implode() it at the end. (This also neatly solves the trailing-comma problem.)
Array constants are nifty for implementing named parameters to functions.
Enable NOTICE, and if you realy want to STRICT error reporting. It prevents a lot of errors and code smell: ini_set('display_errors', 1); error_reporting(E_ALL && $_STRICT);
Stay away from global variables
Keep as many functions as possible short. It reads easier, and is easy to maintain. Some people say that you should be able to see the whole function on your screen, or, at least, that the beginning and end curly brackets of loops and structures in the function should both be on your screen
Don't trust user input!
I've been developing with PHP (and MySQL) for the last 5 years. Most recently I started using a framework (Zend) with a solid javascript library (Dojo) and it's changed the way I work forever (in a good way, I think).
The thing that made me think of this was your first bullet: Zend framework does exactly this as it's standard way of accessing 'controllers' and 'actions'.
In terms of encapsulating and abstracting issues with different databases, Zend_Db this very well. Dojo does an excellent job of ironing out javascript inconsistencies between different browsers.
Overall, it's worth getting into good OOP techniques and using (and READING ABOUT!) frameworks has been a very hands-on way of getting to understand OOP issues.
For some standalone tools worth using, see also:
Smarty (template engine)
ADODB (database access abstraction)
Declare variables before using them!
Get to know the different types and the === operator, it's essential for some functions like strpos() and you'll start to use return false yourself.

Categories