Sie sind auf Seite 1von 11

Functions

Working With Functions


Functions are useful because they make it possible to treat a related group of PHP statements as a single unit.

Defining Functions
The lines of a code that make up a function are called the function definition. The syntax for defining a function is as follows <?php function name_of_function(parameters){ statements; } ?>

Parameters
Parameters are placed within the parentheses that follow the function name. A parameter is a variable that is used within a function. You can also assign default values to a parameter.

Parameters
function computeX($number){ echo $number; } ================== =============
function sample($num1=10,$num2=5){ echo <p>$num1</p>; echo <p>$num2</p>; }

Parameter
You can specify default values for parameters. If you specify default values for parameters, those parameters are optional.
You can call the function without specifying those parameters. The default value will be used.

Parameters
function sayHello($color,$size=2,$face=Arial){ echo <font color=\$color\ size=\$size\ face=\$face\>Hello <br /> </font>; } sayHello(red); sayHello(blue,5); sayHello(green,5,Courier);

Calling Function
function printCompanyName($name){ echo <p>$name</p>; } printCompanyName(Course Technology); Note: Unlike variables, function are case insensitive. This means that you can call printCompanyName() function with any of the ff. statements.

Returning Values
$returnValue= aveNumber(1,2,3); function aveNumber($a,$b,$c){ $sum=$a+$b+$c; $result=$sum/3; return $result; } A return statement is a statement that returns a value to the statement that called the function, which calculates the average of three numbers.

Understanding Variable Scope


Variable Scope: refers to where in your program a declared variable can be used. A global variable is one that is declared outside a function and is available to all parts of your program. A local variable is declared inside a function and is only available within the function in which it is declared.

Activity
1. Create a function named greetings, include three parameters inside it. When the function name greetings is called, it should print the words: Hi, Hello, Goodbye! Save your file as functionGreetings.html 2. Create a function named calculateSquare include one parameter inside it named number, as you call the name of your function it should display the square of the number. Try to pass a parameter value of 9 to the variable number. 3. Create a function named equivalentGrade, include two parameter inside named rawScore and totlScore. When the function is called the ff. output is displayed in the browser: Given: rawScore=50 totlscore=100 A raw score of 50 is equivalent to 75%.

Das könnte Ihnen auch gefallen