Commen3
Transcript
Commen3
2013/14 BASI LINGUAGGIO 2014-‐2015 Programmazione Web 1 Commen0 • Riga singola // This is a comment • Riga mul>pla /* This is a sec>on of mul>line comments which will not be interpreted */ 2014-‐2015 Programmazione Web 2 1 2013/14 Istruzioni • Un file può contenere molto blocchi php • Istruzioni nello stesso blocco php sono divise da ; • In alcuni casi si può omeJere – se ho il tag di chiusura – se ci sono le graffe 2014-‐2015 Programmazione Web 3 Programmazione Web 4 Alcuni errori • Errore 1 • Errore 2 • Soluzioni errore 2: 2014-‐2015 2 2013/14 Iden0ficatori • Nomi ammessi per – variabili – funzioni – costan> – classi • Il primo caraJere deve essere: – una leJera minuscola o maiuscola – un _ (undescore) – un caraJere ASCII tra 0x7f e 0xFF • I successivi possono essere anche 0–9 2014-‐2015 Programmazione Web 5 Variabili • Le variabili sono precedute dal simbolo $ – e poi l'iden>ficatore (case sensi>ve) • alcuni nomi non sono ammessi (es. $this) • Non vanno dichiarate, ne inizializzate – basta usarle e sono create 2014-‐2015 Programmazione Web 6 3 2013/14 Tipi di dato • Tipi scalari – – – – boolean integer float string • Tipi compos> – array – object • Tipi speciali – resource – NULL – callable 2014-‐2015 Programmazione Web 7 Interi • Range: da −2,147,483,648 a +2,147,483,647 – ossia -‐2^31; 2^31-‐1 (range dei long) Per verificare se una variabile è un intero si può usare is_int() o is_integer() Per vedere una variabile su usa var_dump() 2014-‐2015 Programmazione Web 8 4 2013/14 Floa0ng Point • Range posi>vo: da 2.2E-‐308 a 1.7E+308 – a 32 bit takePer careverificare to avoidswriting code that numbers are represented e una variabile è uassumes n float si floating-point può usare is_float() o is_real() completely accurately, such as directly comparing two floating-point values using ==. confron> aJen> alle approssimazioni TheNei normal approach is to compare to several decimal places: if (intval($a * 1000) == intval($b * 1000)) { // numbers equal to three decimal places } Use the is_float() function (or its is_real() alias) to test whether a value is a floating2014-‐2015 Programmazione Web 9 point number: if (is_float($x)) { // $x is a floating-point number } Strings Boolean Because strings are so common in web applications, PHP includes core-level support for creating and manipulating strings. A string is a sequence of characters of arbitrary length. String literals are delimited by either single or double quotes: • Sono 'big dog'falso "fat hog"keyword false – The Variables areinteger expanded – The 0 (interpolated) within double quotes, while within single quotes they are not: – The floa>ng-‐point value 0.0 $name = "Guido"; – The empty string ("") and the string "0" echo "Hi, $name\n"; – An array with zero elements echo 'Hi, $name'; – An object with no values or func>ons Hi, Guido Hi, $nameNULL value – The Double quotes support a variety of string escapes, as listed in Table 2-2. • TuJo il ralso esto è vero • Keyword: true, false Table 2-2. Escape sequences in double-quoted strings Escape Character represented – sequence case insensi>ve \" Double quotes \r 2014-‐2015 Carriage return \t Tab \\ Backslash \$ Dollar sign \{ Left brace \} Right brace \[ Left bracket \] Right bracket Per una variabile è un boolean si può usare is_bool() \n verificare se Newline 24 | Chapter 2: Language Basics Programmazione Web 10 5 2013/14 Esempi take care to avoid writing code that assumes floa completely accurately, such as directly comparing The normal approach is to compare to several dec if (intval($a * 1000) == intval($b * 1000)) { // numbers equal to three decimal places } Use the is_float() function (or its is_real() alias point number: if (is_float($x)) { // $x is a floating-point number } 2014-‐2015 Programmazione Web 11 Strings Because strings are so common in web applicatio for creating and manipulating strings. A string is a length. String literals are delimited by either single String 'big dog' • Sono sequenze di caraJeri ad 1 "fat byte hog" • Possono essere definite con Variables apici singoli o doppi (interpolated) within doub are expanded they are not: $name = "Guido"; echo "Hi, $name\n"; echo 'Hi, $name'; • Differenze fra apici – Interpretazione del testo – Sequenze di escape • singolo apice solo \\ e \' • doppio apice quasi tuJe – \n, \r, \t, etc. Hi, Guido Hi, $name Double quotes also support a variety of string esc Escape sequences in double-quoted strings Per verificare se una variabile è un string si può Table usare i2-2. s_string() 2014-‐2015 Programmazione Web Escape sequence 12 Character represented \" Double quotes \n Newline \r Carriage return \t Tab \\ Backslash \$ Dollar sign 6 2013/14 Stringhe mul0riga • Sintassi: <<<iden>ficatore – dalla riga successiva inizia a definire la stringa – fino a che non trova una riga che con>ene solo l'iden>ficatore • e se necessario il ; – definisce stringhe equivalen> a quelle con " 2014-‐2015 Programmazione Web 13 Array • Gruppo di valori iden>fica> da un numero o o da un nome Per verificare se una variabile è un array si può usare is_array() 2014-‐2015 Programmazione Web 14 7 2013/14 Array 2 2014-‐2015 Programmazione Web 15 Accesso • Posso accedere ad un valore dell'array mediante la chiave • La chiave può essere inserita senza apici, con apici singoli o doppi, o mediante una variabile contenente la chiave 2014-‐2015 Programmazione Web 16 8 $x $x $y $y = = = = 5; true; ""; false; // // // // $x has a true value clearer way to write it $y has a false value clearer way to write it Use the is_bool() function to test whether a value is a Boolean: if (is_bool($x)) { // $x is a Boolean } 2013/14 Arrays An array holds a group of values, which you can identify by position (a number, with zero being the first position) or some identifying name (a string), called an associative index: $person[0] = "Edison"; $person[1] = "Wankel"; $person[2] = "Crapper"; Loop su array $creator['Light bulb'] = "Edison"; $creator['Rotary Engine'] = "Wankel"; $creator['Toilet'] = "Crapper"; The array() construct creates an array. Here are two examples: $person = array("Edison", "Wankel", $creator = array('Light bulb' => 'Rotary Engine' => 'Toilet' => "Crapper"); "Edison", "Wankel", "Crapper"); There are several ways to loop through arrays, but the most common is a foreach loop: foreach ($person as $name) { echo "Hello, {$name}\n"; } foreach ($creator as $invention => $inventor) { echo "{$inventor} created the {$invention}\n"; } Hello, Edison Hello, Wankel Hello, Crapper Edison created the Light bulb Wankel created the Rotary Engine Crapper created the Toilet 2014-‐2015 Programmazione Web 17 26 | Chapter 2: Language Basics Elemen0 non inizializza0 2014-‐2015 Programmazione Web 18 9 Classes are the building blocks of object-oriented design. A class is a Use the is_array() function to test whether a value is an array: structure that contains properties (variables) and methods (functions). if (is_array($x)) { fined with the class keyword: // $x is an array } class Person { There are functions for returning the number public of items in the array, fetching every value $name = ''; in the array, and much more. Arrays are covered in-depth in Chapter 5. function name ($newname = NULL) { if (!is_null($newname)) { $this->name = $newname; PHP also supports object-oriented programming} (OOP). OOP promotes clean modular 2013/14 Objects design, simplifies debugging and maintenance, and assists with code reuse. PHP 5 has return $this->name; a new and improved OOP approach that we }cover in Chapter 6. Objects } Classes are the building blocks of object-oriented design. A class is a definition of a structure that contains properties (variables) and methods (functions). Classes are de- can be made from it w Once a class is defined, any number of objects fined with the keyword: • Classi in class OOP word, and the object’s properties and methods can be accessed with th class Person { public $name = ''; function name ($newname = NULL) { if (!is_null($newname)) { $this->name = $newname; } } $ed = new Person; $ed->name('Edison'); echo "Hello, {$ed->name}\n"; $tc = new Person; $tc->name('Crapper'); echo "Look out below {$tc->name}\n"; Hello, Edison Look out below Crapper return $this->name; } Once a class is defined, any number of objects can be made from it with the new keyword, and the object’s properties and methods can be accessed with the -> construct: Per verificare se una variabile è un object si può usare is_object() $ed = new Person; $ed->name('Edison'); 2014-‐2015 Programmazione Web echo "Hello, {$ed->name}\n"; $tc = new Person; $tc->name('Crapper'); echo "Look out below {$tc->name}\n"; 19 Hello, Edison Look out below Crapper Resources Data Types | 27 • Con>ene il riferimento ad una risorsa esterna – db, file, xml, qp, imap, etc. Per verificare se una variabile è una resource si può usare is_resource() 2014-‐2015 Programmazione Web 20 10 2013/14 Callback • Riferimen> a delle funzioni Callbacks Callbacks are functions or object methods used by some functions, such as call_user_func(). Callbacks can also be created by the create_function() method and through closures (described in Chapter 3): $callback = function myCallbackFunction() { 2014-‐2015 Programmazione Web echo "callback achieved"; } 21 call_user_func($callback); callback achieved NULL NULL • Rappresenta una variabile di qualunque >po senza There’s only one value of the NULL data type. That value is available through the casevalore insensitive keyword NULL. The NULL value represents a variable that has no value (similar to Perl’s undef or Python’s – non è case sensi>ve None): $aleph $aleph $aleph $aleph = = = = "beta"; null; Null; NULL; // variable's value is gone // same // same Use the is_null() function to test whether a value is NULL—for instance, to see whether a variable has a value: if (is_null($x)) { // $x is NULL } Per verificare se una variabile è NULL si può usare is_null() Variables 2014-‐2015 Programmazione Web 22 Variables in PHP are identifiers prefixed with a dollar sign ($). For example: $name $Age $_debugging $MAXIMUM_IMPACT 11 A variable may hold a value of any type. There is no compile-time or runtime type checking on variables. You can replace a variable’s value with another of a different 2013/14 Assegnare valori • L'operatore = assegna il valore alle variabili – da un literal – da un'altra variabile 2014-‐2015 Programmazione Web 23 Programmazione Web 24 Esempi 2014-‐2015 12 2013/14 Assegnare riferimen0 • Si possono creare degli alias delle variabili $var1 "PHP" $alias 2014-‐2015 Programmazione Web 25 Confronto assegnazioni 2014-‐2015 Programmazione Web 26 13 2013/14 Variabili di variabili 2014-‐2015 Programmazione Web 27 Variabili predefinite • • • • • • • • • • • • • • $GLOBALS — References all variables available in global scope $_SERVER — Server and execu>on environment informa>on $_GET — HTTP GET variables $_POST — HTTP POST variables $_FILES — HTTP File Upload variables $_REQUEST — HTTP Request variables $_SESSION — Session variables $_ENV — Environment variables $_COOKIE — HTTP Cookies $php_errormsg — The previous error message $HTTP_RAW_POST_DATA — Raw POST data $hSp_response_header — HTTP response headers $argc — The number of arguments passed to script $argv — Array of arguments passed to script 2014-‐2015 Programmazione Web 28 14