PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.

Slides:



Advertisements
Similar presentations
Objectives Using functions to organize PHP code
Advertisements

PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Entity Framework Performance SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Bogomil Dimitrov Technical Trainer Software.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
JavaScript, Fourth Edition
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Working with Forms in PHP HTTP GET / POST, Validation, Escaping, Input Types, Submitting Arrays, URL Redirecting, PHP Superglobals Svetlin Nakov Technical.
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Repeating Code Multiple Times
Conditional Statements, Loops, Exit, Require
Objectives In this chapter, you will:
Presentation transcript:

PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers

Table of Contents 1.Loops  While, Do…While, For, Foreach 2.Functions, Return and Exit 3.Variable Scope 4.Include and Require 5.Exception Handling 2

Loops

4  While loops are the simplest type of loop in PHP  Repeat a block of code while a certain condition is true:  The body consists of one or more statements  If more than one, surrounding brackets are required  The condition expression is of type boolean While Loop while (expr) { statement; statement;} while (expr): statement; statement;endwhile;

5  Printing the numbers from 1 to 10: While Loop – Example <?php $counter = 1; $counter = 1; while ($counter <= 10) { while ($counter <= 10) { echo " $counter "; echo " $counter "; $counter++; $counter++; }?>

6  While loops have alternative syntax, without { }  Printing the Unicode characters from to ᎈ While Loop – Alternative Syntax <?php $charCode = 0; while ($charCode while ($charCode -> &# ; -> &# ;

7  Do-while loops repeat a code block until some condition breaks  The loop expression is checked at the end of each iteration  The loop body executes at least once Do { … } While() <?php $i = 10; do { echo $i. "\n"; // prints 10, 9, 8, …, 0 echo $i. "\n"; // prints 10, 9, 8, …, 0 $i--; $i--; } while ($i > 0); ?>

While Loops Live Demo

 The classical for -loop syntax is:  Consists of  Initialization statement  Boolean test expression  Update statement  Loop body block For Loops for (initialization; test; update) { statements; } 9

 A simple for -loop to print the numbers : For Loop – Examples for ($number = 0; $number < 10; $number++) { echo $number. " "; echo $number. " ";}  A simple for -loop to calculate n!: $n = 5; $factorial = 1; for ($i = 1; $i <= $n; $i++) { $factorial *= $i; $factorial *= $i;} 10

11  Printing blocks of different colors: For-Loop – Alternative Syntax <?php for ($r=0, $g=0, $b=0; $r < 256; $r+=16, $g+=8, $b+=4) : $color = "#". $color = "#". str_pad(dechex($r), 2, '0'). str_pad(dechex($r), 2, '0'). str_pad(dechex($g), 2, '0'). str_pad(dechex($g), 2, '0'). str_pad(dechex($b), 2, '0'); str_pad(dechex($b), 2, '0');?> "> ">

For-Loops Live Demo

13 Foreach  The foreach construct iterates over arrays and objects  Iterate over the values in array:  Iterate over the key-value pairs in associative array: foreach (array_expression as $value) { statements; statements;} foreach (array_expression as $key => $value) { statements; statements;}

14 Foreach – Examples $colors = array("red", "green", "blue", "yellow", "orange"); foreach ($colors as $value) { echo "$value "; echo "$value ";} $colorMap = array( "red" => "#F00", "green" => "#0F0", "blue" => "#00F"); "red" => "#F00", "green" => "#0F0", "blue" => "#00F"); foreach ($colorMap as $key => $value) { echo " $key -> $value "; echo " $key -> $value ";}

15  Iterating over object properties: Foreach – Alternative Syntax <?php $colors = (object)[]; $colors->red = "#F00"; $colors->slateblue = "#6A5ACD"; $colors->orange = "#FFA500"; foreach ($colors as $key => $value) : ?> "> "> -> ->

Foreach Live Demo

Functions

18 Functions  Functions are named blocks of code  Declared with the keyword function  Can accept parameters and return value  Help organize and reuse the code function rectangleArea($sideA, $sideB) { return $sideA * $sideB; return $sideA * $sideB;} echo rectangleArea(5, 6);

19 Default Parameter Values function strIsEqual($str1, $str2, $ignoreCase = true) { if ($ignoreCase) if ($ignoreCase) return strtolower($str1) == strtolower($str2); return strtolower($str1) == strtolower($str2); else else return $str1 == $str2; return $str1 == $str2;} echo strIsEqual("nakov", "NaKOv", true); // 1 (true) echo strIsEqual("nakov", "NAKOV"); // 1 (true) echo strIsEqual("nakov", "Nakov", false); // "" (false)

Functions Parameters: Pass by Reference  By default PHP passes arguments to functions by value  Changed arguments in the function will be lost after it ends  To force pass by reference use the & prefix function changeValue(&$arg) { $arg += 100; $arg += 100;} $num = 2; echo $num. "\n"; // 2 changeValue($num); echo $num; //

Variable Number of Arguments  PHP supports variable-length function arguments  Read the arguments: func_num_args() and func_get_args() function calcSum() { $sum = 0; $sum = 0; foreach (func_get_args() as $arg) { foreach (func_get_args() as $arg) { $sum += $arg; $sum += $arg; } return $sum; return $sum;} echo calcSum(1, 2), ' '; // 3 echo calcSum(10, 20, 30), ' '; // 60 echo calcSum(10, 22, 0.5, 0.75, 12.50), ' '; //

Returning Values from a Function  Functions can return values with the return statement  Accepts only one argument – the value to be returned  Exits the function  To return multiple values you can use arrays  It’s not obligatory for a function to return a value function example($arg) { return true; return true; // The following code will NOT be executed // The following code will NOT be executed echo $arg + 1; echo $arg + 1;} 22

 You can use fixed-size arrays to return multiple values  The list keyword assigns multiple variables from array items  list is NOT a function, but a language construct  Works only for numerical arrays and assumes indexes start at 0 Returning Multiple Values from a Function function smallNumbers() { return [0, 1, 2]; return [0, 1, 2];} list($a, $b, $c) = smallNumbers(); echo "\$a = $a; \$b = $b; \$c = $c"; 23

Variable Functions  PHP supports variables holding a function  The function name is stored as string value  Can be invoked through the () operator function printSomething($arg) { echo "This is function. Arg = $arg"; echo "This is function. Arg = $arg";} $a = 'printSomething'; $a(5); // This invokes the printSomething(5) function 24

 You can check if function is declared with function_exists($name)  Functions can be nested (declared inside other functions)  Once the first function is called, the second gets globally defined Few Notes on Functions if (!function_exists('func')) { function func($arg) { return true; } function func($arg) { return true; }} function first($args) { function second($args) { … } function second($args) { … } second('hello'); second('hello');} 25

26  Anonymous functions are inline functions with no name  Implemented by closures Anonymous Functions $array = array("Team building: 6-7 September 2014, Pirin", "Nakov", "studying programming", "SoftUni"); usort($array, function($a, $b) { return strlen($a) - strlen($b); return strlen($a) - strlen($b); }); print_r($array);

Functions Live Demo

28  The exit statement ends the PHP script execution immediately  Used for fatal errors, e.g. missing file / resource / database  If the statement is a number, it returns the exit code of the process  If it is a string, the value is printed before the process terminates Exit <?php $filename = '/path/to/data-file'; $file = fopen($filename, 'r') or exit("Unable to open file: $filename"); or exit("Unable to open file: $filename");?>

29  The function die() is an alias for the exit statement:  The message is required  The die() function prints a message and exits the current script: Die $db = mysql_connect("localhost", $username, $password); if (!$db) { die("Could not connect to database"); die("Could not connect to database");} die(message);

Exit Live Demo

Variables Scope

 The arrays $_GET, $_POST, $_SERVER, $_REQUEST and other built-in variables are global  Can be accessed at any place in the code  Variables, declared in functions  Exist only until the end of function (local function scope)  Files being included inherit the variable scope of the caller  Variables declared outside of a function are not accessible in it $name = $_GET['firstName']. $_GET['lastName']; 32

The Global Keyword  Variables outside of a function are not accessible in it:  To access an external variable use the global keyword $a = "test"; // global scope function foo() { echo $a; // this will not output anything (local scope) echo $a; // this will not output anything (local scope)}foo(); $a = "test"; function foo() { global $a; // the global variable $a is included in the scope global $a; // the global variable $a is included in the scope echo $a; // this will output "test"; } echo $a; // this will output "test"; }foo(); 33

Loops and Variable Scope  Variables, declared in loops are accessible after the loop ends  A variable in PHP is declared with its first assignment for ($i = 0; $i < 5; $i++) { $arr[] = $i; $arr[] = $i;} print_r($arr); // outputs 0, 1, 2, 3, 4 $a = 15; if ($a == 5) $five = 'five'; else $five = 'not five'; echo $five; // not five 34

35  Static variables in PHP are initialized only once (on demand)  Their existing values are preserved in the next function calls Static Keyword function callMe() { static $count = 0; // initialized at the first call static $count = 0; // initialized at the first call $count++; // executed at each function call $count++; // executed at each function call echo "callMe() is called $count times\n"; echo "callMe() is called $count times\n";} callMe(); // callMe() is called 1 times callMe(); // callMe() is called 2 times

36  A closure is an anonymous function that can access variables imported from its outside scope (closed in its environment) Closures function nextNumber() { $counter = 0; // the $counter variable gets closed $counter = 0; // the $counter variable gets closed return function() use (&$counter) { return function() use (&$counter) { return ++$counter; return ++$counter; }; };} $f = nextNumber(); echo $f(). "\n"; // 1 echo $f(). "\n"; // 2 echo $f(). "\n"; // 3

Include and Require Including a Script from Another Script

Include and Require  include and require load and evaluate a file holding PHP code  Useful to structure and reuse the code  Both accept single parameter – a file name  Difference between include and require :  If file is not found include produces a warning  require produces a fatal error require "header.php"; echo "page body comes here"; include "footer.php"; 38

 With include and require you can include one file many times and each time it is evaluated  With include_once and require_once if file is already included, nothing happens  For instance if in the file you have declared a function, double including will produce error "Function with same name already exists"  Example: include_once and require_once require_once "functions.php"; 39

Include and Require Live Demo

Exception Handling Catch and Throw Exceptions

Exception Handling in PHP  Exception handling is used to change the normal code execution flow if an certain error (exceptional condition) occurs  When an exception is thrown  The code following it will not be executed  PHP will try to find the matching "catch" block  If an exception is not caught  A fatal error will be issued with an "Uncaught Exception" message  PHP supports the exception handling paradigm  But its API used the old procedural approach 42

Throwing Exceptions  To throw an exception, use the throw keyword  Exceptions cause a fatal error  But can be caught and handled to do something else <?php if (!file_exists("../include/settings.ini")) { throw new Exception("Could not load settings."); throw new Exception("Could not load settings.");}?> 43

44  PHP supports the classical try-catch-finally statement: Catching (Handling) Exceptions try { $db = new PDO('mysql:host=localhost;dbname=test'); $db = new PDO('mysql:host=localhost;dbname=test'); // If exception is thrown, the catch block is executed // If exception is thrown, the catch block is executed} catch (Exception $e) { // Display the exception’s message // Display the exception’s message echo "Error: ". $e->getMessage(); echo "Error: ". $e->getMessage();} finally { echo "This code is always executed."; echo "This code is always executed.";}

Exception Handling Live Demo

46  PHP supports the classical loop statements  While, do…while, for, foreach  PHP code may define and invoke functions  Functions may take parameters and return value  Including PHP code in another PHP code  include / include_once / require / require_once  Variable scope: local, global and static  PHP supports try-catch-finally Summary

? ? ? ? ? ? ? ? ? PHP Flow Control

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International  Attribution: this work may contain portions from  "PHP Manual" by The PHP Group under CC-BY licensePHP ManualCC-BY  "PHP and MySQL Web Development" course by Telerik Academy under CC-BY-NC-SA licensePHP and MySQL Web DevelopmentCC-BY-NC-SA 48

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg