Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions A function is a block of code with a name. function functionName() { code to be executed; }

Similar presentations


Presentation on theme: "Functions A function is a block of code with a name. function functionName() { code to be executed; }"— Presentation transcript:

1 Functions A function is a block of code with a name. function functionName() { code to be executed; }

2 The function will not execute unless it is called.
function writeMsg() {   echo "Hello world!"; } writeMsg(); // call the function // Hello world! By calling the name of the function, we can use it repeatedly.

3 Variable Scope A variable outside a function is not available inside a function. A variable inside a function is not available outside the function.

4 Information can be passed to functions through arguments
Information can be passed to functions through arguments. An argument is like a variable. function writeMsg($message) { echo $message; } writeMsg("Take me to your leader"); // Take me to your leader

5 Functions can accept multiple arguments, separated by a comma
Functions can accept multiple arguments, separated by a comma. function nameAge($name, $year) { $age = $year; echo "$name is $age years old"; } nameAge("Barack Obama", "1961"); // Barack Obama is 53 years old

6 Function arguments can be given a default value
Function arguments can be given a default value. function setScore($minscore = 25) { echo "The score is $minscore <br />"; } setScore(110); setScore(); // Uses 25 by default setScore(98); setScore(101);

7 Return What if we need to store a value inside a function and use it later? function squareNum($x) { $square = $x * $x; return $square; }

8 Assign the function call to a variable
function squareNum($x) { $square = $x * $x; return $square; } $output = squareNum(4); echo $output; // 16

9 A function may only return one value, but that
value can be an array (or an object). When a function reaches return, the function terminates and the function is exited.

10 Echo the function call to immediately access return function centsToDollars($cents) { $total = $cents / 100; return $total; } echo "$" . centsToDollars(1228); // $12.28

11 Function with array as an argument function passArray($colors) { foreach ($colors as $name) { echo "$name <br />"; } passArray($colors = array("orange", "blue", "green", "red", "purple"));


Download ppt "Functions A function is a block of code with a name. function functionName() { code to be executed; }"

Similar presentations


Ads by Google