$myVar=myFunction(array_reverse(explode('.', $_SERVER['SERVER_NAME'])));
Anything wrong with nesting functions like this?
This is ok as long as you can guarantee that each function will always return the desired type. For instance if a function might return a FALSE value, it may be cast to an unexpected value.
The example provided works because both explode (as called) and array_reverse will both always return an array.
A counter-example:
mysqli_query(mysqli_connect(...), 'INSERT INTO tbl VALUES ....');
Since mysqli_connect may return a resource OR FALSE it shouldn't be chained like this. The return value should always be checked for correctness.
It's totally valid to do this, but keep it readable. If you nest 15 function calls or nest a handful of function callss with several parameters each, you'll have an intensely unfun debugging experience.
No it is perectly valid to do that
It may be a bad practice because it makes the code harder to understand and therefore to maintain.
A good practice to overcome this problem is to comment your code (heavily).
People nest functions like that all of the time. Functions are meant to be used in this way. Since functions can return a value, it is, therefore, meaningful to assign a variable to a function, to get the value of that function into a PHP variable.
Thank god for functions returning values, otherwise, it would be a mess to think of it the other way...
Related
I am having to do:
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
I want to avoid that redundant mention of the variable name. I tried:
htmlspecialchars_decode(&$sourceElement['description']);
and
call_user_func('htmlspecialchars_decode', &$sourceElement['description']);
That did not work. Is this possible in PHP? Call a function on a variable?
You could create your own wrapper function that takes the variable by reference:
function html_dec(&$str) {$str = htmlspecialchars_decode($str);}
Then call:
html_dec($sourceElement['description']);
The correct solution would be to include that "redundant" variable mention. It's far more readable, and far less confusing that way.
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
Your way of thinking is good though, you're thinking how to shorten your code, like a true lazy programmer =)
It depends on function. htmlspecialchars_decode() returns the result, it doesn't modify the original variable. And you can do nothing about it.
Most functions in PHP are immutable in mature, i.e. they don't modify the arguments you pass into them. This has a few advantages, one of them being able to use their return value in expressions without side effects.
Here's a generic wrapper you could use to mimic mutable behaviour for any function that takes a single argument:
function applyFn(&$s, $fn)
{
return $s = $fn($s);
}
applyFn($sourceElement['description'], 'htmlspecialchars_decode');
applyFn($sourceElement['description'], 'trim'); // trim string
Mileage may vary :)
Ok, first of all, i suspect this is going to be closed.
Right, i have a question relating to using function calls inside statements as opposed to assigning to a variable first.
For example:
(code is in php, but question applies generally. Also, code is overly simplified)
if (myAmazingFunction() === true) {
// do something amazing
}
instead of
$amazingresult = myAmazingFuncton();
if ($amazingResult === true) {
// do something amazing
}
The question is:
Is there any performance, or other underlying pros or cons to each approach
Stylistically, is any of the approaches considered better than the other
In most languages, there will be no performance difference. In the first case, the compiler will allocate storage for the result of the function call before checking whether it is true. In the second case you're simply making this explicit.
If you are debugging, sometimes the second form is easier, as you can set a breakpoint on the second line and check the value returned by the function before the comparison is made - but then you see the result of the function by the path the executing code takes anyway in the example you've given. You can also re-use the value without rerunning the function, as Zac says in his comment.
Stylistically, this is going to be largely subjective. The only thing I'd say here is that if your variable name makes the purpose of the function output clear, then you might be adding something to the ability for others to understand your code easily.
#DavidM's answer is correct. However, I'd just like to add that stylistically, I think it depends on the name of the function and its context.
Example:
if ($food->tastesGood()) {
echo 'Mmmm!';
}
// vs.
$foodTastesGood = $food->tastesGood();
if ($foodTastesGood) {
echo 'Mmmm!';
}
In this case, it's very clear that the return value of the method tastesGood() is going to be a boolean from both the name of the method and its context. Using a temporary variable adds nothing to your code except making it redundant and less-readable at a glance. In addition, if the variable is not defined right before its used, then you have to go find the definition to understand the condition. In these cases, I would say use of a variable is worse.
Another example:
if ($dishes->wash() !== FALSE) {
echo 'Sparkly!';
}
// vs.
$dishesAreClean = $dishes->wash() !== FALSE;
if ($dishesAreClean) {
echo 'Sparkly!';
}
In this case, we can't really infer the return type of the wash() method from its name, and indeed, it would seem that it returns nothing on success and FALSE on errors. Checking if the dishes are clean then requires us to make sure that there were no errors, but the first case doesn't make for particularly readable or self-documenting code. The second case, however, adds very explicit information about what's going on by way of the temporary variable. In these cases, I would say use of a variable is better.
Is there any performance, or other underlying pros or cons to each approach
Performance-wise, assigning an extra variable that you will use only in your if condition will use extra memory, and one useless line of code. So it will use more memory. Will it be noticeable? Probably not.
Stylistically, is any of the approaches considered bad
Using the method in your if statement is perfectly valid, and I think it's a better approach, since you can read the code and see exactly what value is being tested in the if condition. No need to look for the variable and search where it was affected.
Example:
function create_pets(&$cats, &$dogs){
$dogs = get_dogs();
$cats = get_cats();
}
so I would call it like:
function foo(){
create_pets($cats, $dogs);
// here use $cats and $dogs variables normally
}
I know that I could just assign a new varible the return value of one of those getter functions, but this is just an example. In my situation there's more than just a getter...
The answer as everyone says is "it depends". In your specific example, a "create" function, the code is less obvious to work with and maintain, and thus it's probably a good idea to avoid this pattern.
But here's the good news, there's a way of doing what you are trying to do that keeps things simple and compact while using no references:
function create_pets(){
return array(get_dogs(), get_cats());
}
function foo(){
list($dogs, $cats) = create_pets();
//here use $cats and $dogs variables normally
}
As you can see you can simply return an array and use the list language construct to get the individual variables in a single line. It's also easier to tell what's going on here, create_pets() is obviously returning new $cats and $dogs; the previous method using references didn't make this clear unless one inspected create_pets() directly.
You will not find a performance difference of using either method though, both will just work. But you'll find that writing code that is easy to follow and work on eventually goes a long way.
It depends on the circumstance. Most of the time you would usually call variables by value but in certain situations where you want to modify a variables content without changing the variable's value in other parts of the code, then calling by reference is a good idea. Other wise if you only want the actual content and only the actual content then calling by value is a better idea. This link explains it real well. http://www.exforsys.com/tutorials/c-language/call-by-value-and-call-by-reference.html
I have a basic programming question. I would like to know if every non-void function should have an "return" statement in PHP script.
Take the following two example functions. Which one would be the better way to program? They both do the same thing (to my understanding) but which is the "better practice" and why?
function displayApple1($str){
if($str == 'apple')
echo $str;
}
function displayApple2($str){
if($str == 'apple')
echo $str;
else
return;
}
Overuse of return is a bad thing. Your execution paths should be simple and straightforward; overuse of the return keyword can imply (improper) complexity.
Your second example hurts my head. It should probably read:
funciton displayApple2($str){
if($str == 'apple')
echo $str;
return;
}
Personally, I don't use return statements if I am not specifically returning something.
You should not have a return statement in all functions.
When it does nothing it is just one more line of code.
I lean toward "less code is better" on the grounds that the result is easier to read and offers fewer places for bugs to hide.
Only use a return when you need to, otherwise let the language do it's thing.
If you don't return something from a C function, then the return value becomes whatever random value was previously in RAM at the time you called the function. This is undesirable because a function with no return appears to be returning random values. Therefore, in C you should always have a return statement in every non-void C function so you're not returning random garbage.
PHP doesn't have this problem - if you don't use a return statement, functions are guaranteed to return null, so it is better to leave them out and save some space.
Well I don't know about returning a value on a "funciton", but what use it will have for you? Use it when you think this is good for your situation. Make a clean and useful code is a good practice too :)
[tangent]
I had a teacher dock me 5% on a test for not putting a return statement at the end of a void function in C.
Suffice to say I didn't take any more classes from her.
[/tangent]
No, because Less Code = More Fun ^^
Btw, I believe that Functions without returns should be Subroutines.
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.