1 PHP Introduction Chapter 1. Syntax and language constructs.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Objectives Using functions to organize PHP code
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
PHP Introduction.
True or false A variable of type char can hold the value 301. ( F )
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
JavaScript, Fourth Edition
ASP.NET Programming with C# and SQL Server First Edition
JavaScript, Third Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Basic Elements of C++ Chapter 2.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
ALBERT WAVERING BOBBY SENG. Week Whatever: PHP  Announcements/questions/complaints.
Chapter 4 – The Building Blocks Data Types Literals Variables Constants.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Variables, Operators and Data Types. By Shyam Gurram.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CHAPTER 2 PART #4 OPERATOR 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101 By: Asma Alosaimi Edited.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
1 Working with Data Types and Operators. 2 Using Variables and Constants The values stored in computer memory are called variables The values, or data,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
Flow of Control Part 1: Selection
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Creating PHP Pages Chapter 6 PHP Variables, Constants and Operators.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
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,
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Chapter Topics The Basics of a C++ Program Data Types
Basic Elements of C++.
Data Types, Identifiers, and Expressions
JavaScript Syntax and Semantics
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 2: Basic Elements of Java
PHP.
elementary programming
PHP an introduction.
Chap 7. Advanced Control Statements in Java
Presentation transcript:

1 PHP Introduction Chapter 1. Syntax and language constructs

PHP’s Type Strength PHP is a dynamically typed language (a.k.a. weakly typed language): ○ The type of a variable is not / cannot be (!) declared when you create a new variable ○ The type of a variable is automatically determined by the value assigned to it ○ The type of a variable can change throughout the program according to what is stored in it at any given time $totalqty = 0; // integer $totalamount = 0.00; // float $totalamount = ‘Hello’; // string 2

PHP’s Type Casting You can force a data type by type casting ○ Syntax: put target type in parentheses in front of variable/expression you want to cast (similar to Java): $totalqty = 0; $totalamount = (float) $totalqty; // $totalamount variable will be of type float and // cast variable doesn’t change types! Built-in functions are also available to test and set type (see later) 3

Constants  Use the define() function to create a constant define("CONSTANT_NAME", value);  Constant names: Do not begin with a dollar sign (!) It is common practice to use all uppercase letters for constant names Are case sensitive by default (this can be changed, but not recommended!)  The value you pass to the define() function can only be a scalar value: a string, integer, float, or boolean value define(“VOTING_AGE”, 18); echo “ The legal voting age is ”, VOTING_AGE, " ";  Note no $ sign precedes constant names in expressions!  A constant’s name cannot be used as variable names within the quotation signs surrounding a string!  A list of predefined vars and constants can be obtained calling phpinfo() 4

Variables’ Scope I. PHP superglobals: 5

Variables’ Scope - 6 basic scope rules I. Built-in superglobal or autoglobal variables are visible everywhere (=globally) within a script, both inside and outside functions.  PHP includes various autoglobals or superglobals, which are predefined global arrays.  Autoglobals contain client, server, and environment information that you can use in your scripts.  Autoglobals are associative arrays – arrays whose elements are referred to with an alphanumeric key instead of an index number. 6

PHP Operators  Arithmetic operators: Binary operators +, -, *, /, %  Usually applied to integers or doubles  String operands are converted to numbers: starting at the beginning of the string up to 1 st non-valid character; if no valid characters, the value of the string will be 0. Unary operators +, -  String operators:. – the string concatenation operator $s1 = “Bob’s ”; $s2 = “Auto Parts”; $result = $s1. $s2; // result now contains the string “Bob’s Auto Parts” 7

Operators  Crash_Course_Examples/operators.php Crash_Course_Examples/operators.php  ples/PHP_Crash_Course/operators_php.pdf ples/PHP_Crash_Course/operators_php.pdf

PHP Operators  Assignment operators: Basic assignment operator =  The value of an assignment expression lhs_operand = rhs_expression is the value that is assigned to lhs_operand  = associates from right to left  expressions like the following one are correct: $a = $b = 6 + $c = 9; // $c is now 9, $a and $b are 15 // can also be written as $a = $b = 6 + ($c = 9); Combined assignment operators: +=, -=, *=, /=, %=,.=  $a += 5;is equivalent to $a = $a + 5; 9

PHP Operators  Assignment operators: Pre- and Post-Increment and Decrement: ++, --  All 4 operators modify the operand and the value of the expression is the old value (post) or the new value (pre) of the operand (like in Java). Reference operator: &  $a = 5; $b = $a;  a copy of the value in $a is made and stored in $b, elsewhere in memory  $b = &$a;  $b is an alias for the same memory location which is referred to as $a = $a and $b are associated with / name the same memory location  $a = 7; //  both $a and $b are now 7  unset($b) breaks the link between name $b and the memory location storing 7 → $b is now undefined 10

PHP Operators  Comparison operators: ==equals ===identical (if operands are equal and of the same type) !=not equal <>not equal !==not identical < > <= >= string comp_op integer → string is converted to a number 0==‘0’ → true 0 === ‘0’ → false string comp_op string → compared as numbers if they are numerical strings… 11

PHP Operators  Logical operators (combine the results of logical conditions): !NOT &&AND ||OR andAND (but lower precedence than &&) orOR (but lower precedence than ||) xorEXCLUSIVE OR ($a xor $b is true when exactly one of $a and $b is true)  The execution operator ``(= a pair of backticks, not quotes!) PHP tries to execute the content between `` as a command at the server’s command line. The value of the expression is the output of that command. Example: $out = `dir`; // on a Win server, the list of files/directories in current directory = where the script is echo “ $out ”; 12

PHP Operators - Precedence & Associativity  Precedence = order in which operations in an expression are evaluated  Associativity = order in which operators of equal precedence are evaluated 13 $a=5; $b=4; ? The value of the following expression? $b + ++$a/2 + 3 == 10

Using Variable Functions  Testing and setting variable types: string gettype(mixed variable) Returns one of the strings: “bool”, “int”, “double”, “string”, “array”, “object”, “resource”, “NULL”, or “unknown type”. “Mixed” – is a pseudo-type / signifies that variables of many (or any) data types are accepted as arguments; or function is “oveloaded” bool settype(mixed variable, string type) Sets the type of “variable” to the new type passed as a second argument. “Type” can be “bool”, “int”, “double”, “string”, “array”, “object”, “resource”, “NULL”. $a = 56; echo gettype($a).’ ’;// displays int settype($a, ‘double’); echo gettype($a).’ ’;// displays double 14

Using Variable Functions  Specific type-testing functions, return true of false is_array(variable) is_double(variable)is_float(variable)is_real(variable) is_long(variable)is_int(variable)is_integer(variable) is_string(variable) is_bool(variable) is_object(variable) is_resource(variable) is_null(variable) is_scalar(variable) – checks whether variable is an integer, boolean, string or float is_numeric(variable) – checks whether variable is any kind of number or a numeric string is_callable(variable) – checks whether variable is the name of a valid function 15

Using Variable Functions  Testing variable status: bool isset(mixed variable1 [, mixed variable2 …] ) Returns true if all variables passed to the function exist and false otherwise void unset(mixed variable1 [, mixed variable2, …]) Gets rid of the variable(s) it is passed bool empty(mixed variable) Checks if variable exists and has a nonempty, nonzero value These functions are very useful for checking (server-side) if the user filled out the appropriate fields in the form; example: echo isset($tireqty); // always true for a textbox field echo empty($tireqty); // depends on user input, false if form field is empty 16

PHP Conditionals  if (condition) statement or code_block where code_block = { statement(s) }  if (condition) statement or code_block else statement or code_block  NOTE: when writing a cascading set of if-else statements “else if” can be also written “elseif”  Conditional operator: condition ? value_if_true : value_if_false  switch Same syntax as Java; control expression and case labels can evaluate to integer, string or float Must use break to end execution after a matching case 17

PHP Conditionals - Example  HTML form contains the following select list: I'm a regular customer TV advertising …  Equivalent if-else and switch statements for processing form data for the select form field: $find = $_POST["find"]; if ($find == "a") echo " Regular customer. "; elseif ($find == "b") echo " Customer referred by TV advertising. "; … switch($find) { case "a": echo " Regular customer. "; break; … } 18

PHP Conditionals - Example  Crash_Course_Examples/orderform_3.h tml Crash_Course_Examples/orderform_3.h tml  ples/PHP_Crash_Course/processorder_ 3_php.pdf ples/PHP_Crash_Course/processorder_ 3_php.pdf

PHP Loop Statements  while ( condition ) // same semantics as in Java statement or code_block  Example - generate a shipping cost table, if prices are proportional to the distance: Distance Cost <?php $distance = 50; while ($distance <= 250 ) { echo " \n $distance \n"; echo " ". $distance/10." \n \n"; $distance += 50; } ?> 20

PHP Loop Statements  Crash_Course_Examples/freight.php Crash_Course_Examples/freight.php  ples/PHP_Crash_Course/freight_php.pd f ples/PHP_Crash_Course/freight_php.pd f

PHP Loop Statements  do statement or code_block while ( condition ); // same semantics as in Java  for (initial-action; loop-continuation-condition; action-after-each-iteration) statement or code_block // same semantics as in Java  Interesting example – combine variable variables with a for loop to iterate through and process a series of form fields with repetitive names, such as name1, name2, name3 etc: for ($i=1; $i<=$numfields; $i++) { $temp = “name$i”; // $i is interpolated! echo $$temp. “ ”; } 22

Alternative Control Structure Syntax  control_structure (expression_or_condition) : statements; special_keyword;  The alternative syntax can be used for: statement special_keyword is: if endif switch endswitch while endwhile for endfor  if ($totalqty == 0) : echo " You didn’t order anything on the previous page! "; exit; endif; 23