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.
Related
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
How is type ignorance implemented in PHP? For example, I can write the function:
function min($n, $m){
if ($n<$m) return $n;
return $m;
}
Then, I could use that function indifferently with integer, real or even string. I believe this is possible because PHP passes pointers instead of real variables (or reference to variables). Am I right? Can someone point me out a good lecture about internal implementation of PHP or a good explanation of how thing are made?
I should add that I am much interested into the way PHP interpreter make it work. Thank for the answers that were provided until now.
Its because PHP is dynamic. Things are passed by value in PHP. Its called duck typing.
http://en.wikipedia.org/wiki/Duck_typing#In_PHP
By default, PHP passes variables by value, not by reference. It is possible to pass by reference by changing function min($n,$m) to function min(&$n, &$m). For more on pass-by-reference, check out this link on the PHP manual
This also may be helpful for you: http://php.net/manual/en/language.variables.scope.php
Are there any circumstances where identically named classes and functions in PHP, could collide or cause problems in any way? For example:
function Foobar(){
// ...
}
class Foobar{
// ...
}
Cursory testing shows that PHP can discern between them based on context.
No, they never collide. But:
Do not do it.
You will confuse everyone if you do so, because I would not expect there to be a function and a class of the same name. Many don't even know it's legal to do so.
When I see an upper case name In PHP (first letter), I assume it is a class. If you put () around it, I will know it's a function. But I wouldn't assume that there is a class of the same name. All you do is confuse people. Some might assume: "Cool, I didn't know you could omit new". I don't know what your intents are, but if it's to get rid of the new keyword - and only that - it's very bad. I will assume you do more than just that, and will go check what that function actually does, and I'll get angry if I find out it does nothing except returning a new instance without doing anything... I just wasted my time looking up a function that does... nothing.
I'm trying to figure out how to know what has been done to a variable.
Here's an example:
function a($hello) {
$out .= strtoupper(ucwords(strtolower($hello)));
return $out;
}
echo function_trace('$hello') // returns array(strtoupper,ucwords,strtolower)
Thanks!
Matt
There's not really an easy way to do this, because variables don't store "state" or "history". Stack traces (where you probably got your inspiration from) are possible because they're generated from the existing execution stack, which is stored out of necessity to be able to properly unwind chains of function calls.
In addition, your example is trying to trace a function parameter - but that parameter variable is only defined within the scope of the function. Attempting to reference it outside of the function would result in the interpreter not knowing what variable you're trying to indicate - it'd think you're looking for a globally-scoped $hello, not the one used as an argument in the function.
There's no hook in PHP that does exactly what you want, but you can get a call stack with debug_backtrace():
http://php.net/manual/en/function.debug-backtrace.php
It's not possible to do exactly what you're asking for, but perhaps if you gave a bit more context about what you were hoping to do with that function trace, we could give some suggestions?
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.