In my opinion this tutorial is already following the excellent approach of using small focused examples and building on them. This makes it easier to understand and gives the reader a chance to try some simple experiments without having to wade through the muck of a complex framework.
I assume at some point you will show the type of frameworks you can use in PHP but it would be foolish to burden you reader with those until they understand the basics.
Qualcosa di utile
Andiamo a fare qualcosa di leggermente più utile. Andremo a controllare che tipo di browser sta utilizzando la persona che visita le nostre pagine. Per fare questo si andrà a controllare la stringa dell'user agent che il browser invia come parte della richiesta HTTP. Quest'informazione viene inviata in una variabile. Le Variabili iniziano sempre con il simbolo di dollaro $ in PHP. La variabile alla quale ci riferiamo adesso è $_SERVER["HTTP_USER_AGENT"].
Nota: Note sulle variabili Autoglobali di PHP $_SERVER è una variabile speciale riservata a PHP la quale contiene tutte le informazioni relative al Web Server. È conosciuta come Variabile autoglobale (o Superglobale). Per maggiori informazioni è possibile vedere la pagina del manuale relativa alle Variabili Autoglobali. Questo tipo di variabili sono state introdotte nella versione » 4.1.0 di PHP. Nelle versioni precedenti abbiamo utilizzato le ormai vecchie $HTTP_SERVER_VARS, oggi in disuso, anche se queste continuano ad esistere. (Potete guardare nelle note del vecchio codice.)
Per visualizzare questa variabile, dobbiamo semplicemente:
Example #1 Stampare video una variable (elemento d'Array)
<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>
L'output (risultato) di questo script potrebbe essere:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Ci sono molti types (tipi) di variabili disponibili in PHP. Nell'esempio di sopra abbiamo stampato un elemento di un Array. Gli Array possono essere molto utili.
$_SERVER è soltanto una variabile che automaticamente viene resa diponibile da PHP. È possibile visualizzare una lunga lista nella sezione Variabili riservate del manuale oppure ottenere la lista completa creando un file php nella seguente forma:
Example #2 Mostrare tutte le variabili predefinite di PHP con phpinfo()
<?php phpinfo(); ?>
Se caricate questo documento da un browser riceverete una pagina piena d'informazioni circa PHP, così come la lista di tutte le variabili disponibili.
Potete mettere dichiarazioni multipli di PHP all'interno di un tag di PHP e generare piccoli blocchi di codice che fanno di più di un singolo echo. Per esempio, se desiderassimo controllare per vedere se l'utente usa Internet Explorer potremmo fare qualcosa come questo:
Example #3 Esempi usando le strutture di controllo e le funzioni
<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
echo "Stai usando Internet Explorer<br />";
}
?>
L'output di esempio di questo script potrebbe essere:
Stai usando Internet Explorer<br />
Qui introduciamo una coppia di nuovi concetti. Abbiamo la dichiarazione if (se). Se avete una conoscenza con la sintassi di base usata dal linguaggio C questo dovrebbe sembrare logico per voi. Se non conoscete abbastanza C od un altro linguaggio che utilizza la sintassi qui sopra descritta, dovreste probabilmente prendere qualsiasi libro introduttivo di PHP e leggere i primi capitoli, o leggere la parte del manuale relativa ai Riferimenti del Linguaggio. Potete trovare una lista dei libri di PHP su » http://www.php.net/books.php.
Il secondo concetto che abbiamo introdotto era la chiamata alla funzione strstr(). Questa è una funzione sviluppata in PHP che cerca una stringa all'interno di un'altra stringa. In questo caso abbiamo cercato "MSIE" all'interno della stringa $_SERVER["HTTP_USER_AGENT"]. Se la stringa viene trovata, la funzione restituisce TRUE altrimenti, FALSE. Se restituisce TRUE, la dichiarazione if viene valuta come TRUE ed il codice all'interno dei relativi {braces} (sostegni) sarà eseguito. Altrimenti, non esegue altro. Sentitevi liberi di generare esempi simili, con if, else (altrimenti) ed altre funzioni quali strtoupper() e strlen(). Ogni pagina del manuale, relativa a queste funzioni contiene anche degli esempi pratici.
Possiamo fare un passo avanti e mostrarvi come potete entrare ed uscite dal modo PHP anche dall' interno di un blocco PHP:
Example #4 Intercalare i modi PHP e HTML
<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
?>
<h3>strstr dovrebbe ritornare true</h3>
<center><b>Stai usando Internet Explorer</b></center>
<?php
} else {
?>
<h3>strstr dovrebbe ritornare false</h3>
<center><b>Non stai usando Internet Explorer</b></center>
<?php
}
?>
L'output di esempio di questo script potrebbe essere:
<h3>strstr dovrebbe ritornare true</h3> <center><b>Stai usando Internet Explorer</b></center>
Invece di usare la dichiarazione echo per fare l'output di qualcosa, saltiamo fuori dal modo PHP inviando soltanto HTML puro. Il punto importante da notare qui è che il flusso logico dello script rimane intatto. Solo uno dei blocchi di di HTML finirà per essere inviato come risposta, dipendendo se strstr() ritorna TRUE o FALSE in altre parole, se la stringa MSIE viene trovata o meno.
Qualcosa di utile
04-Oct-2008 01:12
28-Sep-2008 06:08
Ducky,
I have started teaching my 14 year old daughter basics of web development. We've started off with separating document structure form presentation from logic. It's actually worked out well - and she appreciates that it will help her down the road.
Please do NOT underestimate the intelligence of your readership by assuming that such "complex things" as best practices can't be taught from the start. Teaching best practices from the start are the types of things that give students a leg up when they get out into the work force and have to ramp up in new job situations - little things like that do get noticed by employers and coworkers.
02-Sep-2008 08:26
To ducky:
Actually it's a good idea to start the habit of separating logic from presentation since the beginning (like when you're just starting to learn html and css). Otherwise you'll get used to not work that way, and when you want to do it it'll be much harder.
17-Jun-2008 11:25
Seperating logic and presentation should be introduced at start. I'm just learning PHP but have background in Perl, C and C++ and find mixed html/code extremly complex to maintain. It would be very nice if this beginners tutorial already presented on how to seperate code/html. Now to read up on that smarty ;).
23-Apr-2008 12:36
I don't think there is a bad time to start separating logic from presentation. It is actually a good idea to start doing this from the get-go so it becomes a habit. This is a great habit.. Everything now a days is going away from mixing logic and presentation for simplicity sake among other things (look at html and css). I think a good thing to read up on is smarty. It can do wonders separating your logic from presentation.
03-Apr-2008 01:54
To the above poster:
That's probably too much to think about when you're starting out... You should probably at first just concentrate on getting the stuff running and learning syntax before you consider best practices and the like.
20-Dec-2006 08:00
While it's easy to get carried away mixing your logic and presentation together since it's so easy to do, your better off using PHP within HTML only to fill in values, or include other source files.
Keep your actual processing in separate libraries that are called before you send any headers to the page. Try to avoid calling a script that retrieves or sets information, or manipulates it in the middle of your HTML. You'll find it's much easier to maintain.
