Is it a good idea to create variables using references? - php

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

Related

Difference in different types of function

This is my first question so please be patience.This question may sounds childish but I really want to know that what is a function in programming? How they are defined and how they are called to execute. I am just learning php. I have seen many functions like this
function myfunction () {
--------
--------
}
and another type function like this
function myfunction (some variables) {
------------
------------
}
I want to know what is the difference in between them? Any help and suggestions or any valuable link will be more appreciated. Before down voting this question any comments or any good learning link will be more helpful to me.
Those functions are exactly the same except for what they are provided (in terms of data). The first one requires no variables to be passed to it externally to run.
The second one has variables it does use that are passed from it externally, however, these may not be required as default values can be set for these variables.
A function in programming is used to perform a repetitive task, such as removing underscores from a string and making the first letter of each word a capital.
To define a variable, the simplest way is to do this:
function my_function () {
// Function code here
}
To call this function, you need to make sure it is accessible (e.g. included on the page), you simply do:
my_function();
That will execute the function and potentially return it's results.
You can also pass variables to functions as stated, but I recommend looking up tutorials on PHP functions.
https://www.google.co.uk/search?q=PHP+Functions ... lots of results for you :-)
This explanation is PHP specific, other languages may vary.

Coding Style: function calls inside statements

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.

PHP call time pass by reference workaround

To simplify escaping strings using mysql_real_escape_string I was hoping to be able to write a function that would take an arbitrary number of arguments and apply the function to them all.
Something like this:
function escape()
{
$args = func_get_args();
array_map('mysql_real_escape_string', $args);
}
As you should be able to see, this would rely on the arguments being passed to this function as references. Given that call time references can't be done in PHP anymore what's the best workaround to this? As I have a not insignificant number of functions that write specific subsets of info to the database I really need a generic function like the above rather than having calls to mysql_real_escape_string everywhere.
My testing has also indicated that arguments passed to mysql_real_escape_string are always passed by value. So even if I could get a reference to escape() my hard work is subsequently destroyed. Is there any way around this?
There must be other people with a similar use case out there but maybe the solution is to just call the function directly. At least I can wrap mysql...... in a function with a shorter name to keep the code cleaner. This may just be a situation where PHP has no equivalent to being able to pass a pointer.
The short answer is, it's not pretty.
The long answer is:
function escape_all(array $args) {
foreach($args as &$arg) {
$arg = mysql_real_escape_string($arg);
}
}
escape_all(array(&$foo, &$bar));

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 is the best way to capture data returned from a function in PHP?

I am new to programming and learning with Wordpress.
the_title(); //outputs the title of the page
I want to capture the title of the page into a string variable so I can manipulate it with strtolower and str_replace functions.
The only way I have gotten it to work is with output buffering.
ob_start();
the_title();
$result = ob_get_clean();
echo str_replace(" ","-",strtolower($result));
/*there has got to be an easier way....
i dont fully understand why */
str_replace(" ","-",strtolower(the_title()));
What am I doing wrong?
If what you really are looking for is the wp_title function, the 2nd argument it takes is a boolean on whether or not it should display it or return it. Pass it false so it will return it to the var, then you can do this:
$mytitle = wp_title(null, false);
Otherwise, your only option is to find the function you're looking for and modify the source code.
There is no easier way. Your function does not return the string, it prints it, therefore you will have to use output buffering if you want to capture the output.
It's the difference between f1() and f2() in the following example.
// Returns a string, prints nothing.
function f1() {
return "String";
}
// Prints a string, returns nothing.
function f2() {
echo "String";
}
Wordpress is a HORRIBLE app to learn how to program from. It uses these global functions that "just work" but they do very specific tasks "inside 'The Loop'". As I say, this is a horrible example of what good code should be.
Thankfully (for you) there are other functions that just return the part you're looking for. Rather than me just writing what you need, you can read a full listing here. Take care that you note down which must be within the mythical Loop and which you can use anywhere.
As it happens there are even more ways to get the title, but I was really imagining for this example you would do something like:
$this_post = get_post($post); // I *think* $post is the post ID inside the loop though I could be wrong
echo $this_post->post_title;
But as another poster (correctly) says you can use a fairly simple wp_title() function to grab the current loop title.
This brings me back to perhaps wanting to explain why learning programming from Wordpress is a bad idea. They have so many damned way of doing the same damned thing that it's almost impossible to keep on top of things.
A blog is a really simple set of data (even moreso in WP's case because it isn't fully normalised) but rather than just having one way to output a title <?php echo $post->title; ?> you have umpteen ways, all doing subtly different things.
If you really want to learn how to program (instead of hacking your way around the crap that is the WP internals), creating a simple blog engine is fairly quick and fun... It's certainly how a lot of people get into a new language or framework.
And if you really want to have fun, have a look at Django.
Enough of the Wordpress rant. If you're fighting something like this in the future that doesn't have 100 ways of doing it, I really wouldn't recommend output-buffer-capturing. It uses up a whole buttload of resources for something relatively simple.
The easiest way can be as simple as just taking the source for the original function, sticking it in a new function and replacing the echo with return.
Just note there may be some database connectivity to handle that returning prematurely may break... So if the echo isn't the last statement, instead of returning right there, store the string as a variable and return at the end of the function.
just figured Id share my final solution with you guys.
This was to give my body tags unique id's in wordpress.*/
$title =wp_title(null,false);
echo strtolower(str_replace(' ','-',ltrim($title)));
//without the ltrim() 2 dashes are created before the title.
Almost every 'the_*' function in Wordpress has a 'get_the_*' counterpart. So, you just have to use
echo str_replace(" ","-",get_the_title());
And it's going to work like a charm. there's also get_the_excerpt(), get_the_content() and the_permalink() which somehow breaks the naming convention (God knows how many times I've written "get_the_permalink()" and got frustrated on why it didn't work)
Cheers!

Categories