Imparare PHP in 10 minuti
PHP è un linguaggio di scripting lato server ampiamente utilizzato, progettato per lo sviluppo web. Originariamente creato per “Pagine Personali”, PHP ora significa “PHP: Hypertext Preprocessor”. Questo tutorial copre le funzionalità di PHP 8.3+, aiutandoti ad apprendere rapidamente lo sviluppo PHP moderno.
1. Scrivere il tuo primo programma PHP
Iniziamo con un programma semplice. Crea un file chiamato hello.php
e inserisci il seguente codice:
<?php
echo "Hello, World!";
?>
Salva il file ed eseguilo usando un server web o PHP CLI:
php hello.php
L’output sarà:
Hello, World!
Questo semplice programma dimostra la funzionalità di output di base di PHP. L’istruzione echo
viene utilizzata per visualizzare il testo. Il codice PHP è racchiuso all’interno dei tag <?php
e ?>
.
2. Sintassi di base
La sintassi di PHP è semplice e simile a C e Perl. Il codice PHP viene eseguito sul server e i risultati vengono inviati al browser come HTML puro.
<?php
// This is a single-line comment
echo "Hello, World!";
/*
This is a multi-line comment
spanning multiple lines
*/
?>
Regole di sintassi di base in PHP:
- Tag PHP: Il codice PHP deve essere racchiuso nei tag
<?php ... ?>
- Commenti: I commenti a riga singola usano
//
o#
, i commenti multi-riga usano/* ... */
- Istruzioni: Terminano con punto e virgola
;
- Sensibilità alle maiuscole: I nomi delle variabili sono sensibili alle maiuscole, ma i nomi delle funzioni non lo sono
- Variabili: Iniziano con il simbolo
$
<?php
$name = "John"; // Variable (case-sensitive)
$Name = "Jane"; // Different variable
echo $name; // Outputs: John
ECHO $Name; // Outputs: Jane (ECHO works same as echo)
?>
3. Variabili e tipi di dati
In PHP, le variabili sono contenitori per memorizzare dati. PHP è un linguaggio a tipizzazione debole, il che significa che non è necessario dichiarare esplicitamente i tipi di variabile.
Regole di nomenclatura delle variabili:
- Deve iniziare con il simbolo
$
- Può contenere lettere, numeri e underscore
- Non può iniziare con un numero
- Sensibile alle maiuscole
Principali tipi di dati PHP:
- String: Dati di testo racchiusi tra virgolette
- Integer: Numeri interi
- Float: Numeri decimali
- Boolean:
true
ofalse
- Array: Raccolta di valori
- Object: Istanza di una classe
- NULL: Rappresenta nessun valore
- Resource: Riferimento a risorse esterne
<?php
$name = "Alice"; // String
$age = 25; // Integer
$height = 5.8; // Float
$is_student = true; // Boolean
$grades = [90, 85, 92]; // Array
$data = null; // NULL
// Type checking
var_dump($name); // string(5) "Alice"
echo gettype($age); // integer
?>
3.1 Operazioni con stringhe
Le stringhe possono essere definite usando virgolette singole o doppie, con comportamenti diversi:
<?php
$single = 'Single quote string';
$double = "Double quote string";
$name = "John";
$greeting = "Hello, $name!"; // Variable interpolation
$greeting2 = 'Hello, $name!'; // No interpolation
echo $greeting; // Hello, John!
echo $greeting2; // Hello, $name!
// String concatenation
$full_name = "John" . " " . "Doe";
$full_name .= " Jr."; // Append
// String functions
echo strlen($name); // String length: 4
echo strtoupper($name); // JOHN
echo strtolower($name); // john
echo substr($name, 0, 2); // Jo
?>
3.2 Array
PHP supporta array indicizzati, array associativi e array multidimensionali:
<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Multidimensional array
$students = [
["name" => "Alice", "grade" => 90],
["name" => "Bob", "grade" => 85],
["name" => "Carol", "grade" => 92]
];
// Accessing arrays
echo $fruits[0]; // apple
echo $person["name"]; // John
echo $students[0]["grade"]; // 90
// Array functions
echo count($fruits); // 3
array_push($fruits, "grape"); // Add element
print_r($fruits); // Display array
?>
4. Operatori
PHP fornisce vari operatori per diverse operazioni:
4.1 Operatori aritmetici
<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition: 13
echo $a - $b; // Subtraction: 7
echo $a * $b; // Multiplication: 30
echo $a / $b; // Division: 3.333...
echo $a % $b; // Modulus: 1
echo $a ** $b; // Exponentiation: 1000
?>
4.2 Operatori di confronto
<?php
$x = 5;
$y = "5";
var_dump($x == $y); // true (equal value)
var_dump($x === $y); // false (identical type and value)
var_dump($x != $y); // false
var_dump($x !== $y); // true
var_dump($x > 3); // true
var_dump($x <= 5); // true
?>
4.3 Operatori logici
<?php
$a = true;
$b = false;
var_dump($a && $b); // false (AND)
var_dump($a || $b); // true (OR)
var_dump(!$a); // false (NOT)
var_dump($a and $b); // false (AND, lower precedence)
var_dump($a or $b); // true (OR, lower precedence)
?>
5. Controllo del flusso
5.1 Istruzioni if
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>
5.2 Istruzioni switch
<?php
$day = "Monday";
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "Weekday";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Invalid day";
}
?>
5.3 Cicli
Ciclo for:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i\n";
}
// foreach for arrays
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// foreach with key-value pairs
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
Cicli while e do-while:
<?php
$count = 0;
while ($count < 3) {
echo "Count: $count\n";
$count++;
}
$num = 0;
do {
echo "Number: $num\n";
$num++;
} while ($num < 3);
?>
6. Funzioni
Le funzioni in PHP sono blocchi di codice riutilizzabili che eseguono compiti specifici:
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Function with default parameters
function calculate_area($length, $width = 1) {
return $length * $width;
}
echo calculate_area(5); // 5 (width defaults to 1)
echo calculate_area(5, 3); // 15
// Variable arguments
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
// Anonymous functions (closures)
$multiply = function($a, $b) {
return $a * $b;
};
echo $multiply(4, 5); // 20
?>
6.1 Ambito delle variabili
<?php
$global_var = "I'm global";
function test_scope() {
global $global_var;
$local_var = "I'm local";
echo $global_var; // Accessible with 'global' keyword
echo $local_var; // Local to this function
}
test_scope();
// Static variables
function counter() {
static $count = 0;
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
7. Programmazione orientata agli oggetti
PHP supporta la programmazione orientata agli oggetti con classi e oggetti:
<?php
class Person {
// Properties
private $name;
private $age;
public $city;
// Constructor
public function __construct($name, $age, $city = "Unknown") {
$this->name = $name;
$this->age = $age;
$this->city = $city;
}
// Methods
public function getName() {
return $this->name;
}
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
}
}
public function getAge() {
return $this->age;
}
public function introduce() {
return "Hi, I'm {$this->name}, {$this->age} years old from {$this->city}";
}
}
// Creating objects
$person1 = new Person("John", 25, "New York");
$person2 = new Person("Jane", 30);
echo $person1->introduce();
echo $person2->getName();
?>
7.1 Ereditarietà
<?php
class Animal {
protected $name;
protected $species;
public function __construct($name, $species) {
$this->name = $name;
$this->species = $species;
}
public function makeSound() {
return "{$this->name} makes a sound";
}
public function getInfo() {
return "{$this->name} is a {$this->species}";
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name, "Dog");
$this->breed = $breed;
}
public function makeSound() {
return "{$this->name} barks";
}
public function fetch() {
return "{$this->name} fetches the ball";
}
}
$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getInfo(); // Buddy is a Dog
echo $dog->makeSound(); // Buddy barks
echo $dog->fetch(); // Buddy fetches the ball
?>
8. Gestione degli errori
PHP fornisce diversi modi per gestire errori ed eccezioni:
<?php
// Try-catch for exceptions
try {
$result = 10 / 0;
throw new Exception("Custom error message");
} catch (DivisionByZeroError $e) {
echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
} finally {
echo "This always executes";
}
// Custom exception class
class CustomException extends Exception {
public function errorMessage() {
return "Custom error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
}
}
try {
throw new CustomException("Something went wrong!");
} catch (CustomException $e) {
echo $e->errorMessage();
}
?>
9. Operazioni sui file
PHP fornisce varie funzioni per la manipolazione dei file:
<?php
// Reading files
$content = file_get_contents("example.txt");
echo $content;
// Writing files
file_put_contents("output.txt", "Hello, PHP!");
// File operations with error handling
if (file_exists("data.txt")) {
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
} else {
echo "File not found";
}
// Working with file handles
$handle = fopen("log.txt", "a");
if ($handle) {
fwrite($handle, "Log entry: " . date("Y-m-d H:i:s") . "\n");
fclose($handle);
}
?>
10. Lavorare con form e HTTP
PHP eccelle nella gestione di form web e richieste HTTP:
<?php
// HTML form (save as form.html)
/*
<form method="POST" action="process.php">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
*/
// Processing form data (process.php)
if ($_POST) {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
// Validation
if (empty($username) || empty($email) || empty($password)) {
echo "All fields are required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process the data
echo "Welcome, " . htmlspecialchars($username);
// Hash password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Save to database, etc.
}
}
// Working with GET parameters
$page = $_GET['page'] ?? 1;
$category = $_GET['category'] ?? 'all';
echo "Page: $page, Category: $category";
?>
11. Operazioni del database
PHP comunemente lavora con database, specialmente MySQL:
<?php
// Database connection using PDO
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb;charset=utf8",
"username",
"password",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Prepared statements (secure)
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND city = ?");
$stmt->execute([18, "New York"]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "User: " . $row['name'] . "\n";
}
// Insert data
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$stmt->execute(["John Doe", "[email protected]", 25]);
echo "Last inserted ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
12. Funzionalità moderne di PHP (PHP 8.0+)
PHP 8.0+ ha introdotto molte funzionalità moderne:
<?php
// Named arguments (PHP 8.0+)
function createUser($name, $email, $age = 18, $active = true) {
return compact('name', 'email', 'age', 'active');
}
$user = createUser(
name: "John",
email: "[email protected]",
active: false
);
// Match expression (PHP 8.0+)
$status_code = 200;
$message = match($status_code) {
200, 201 => 'Success',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown Status'
};
// Nullsafe operator (PHP 8.0+)
$user_name = $user?->profile?->name ?? 'Unknown';
// Constructor property promotion (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
public int $age = 18,
private bool $active = true
) {}
public function isActive(): bool {
return $this->active;
}
}
$user = new User("John", "[email protected]", 25);
echo $user->name; // John
// Enums (PHP 8.1+)
enum Status {
case PENDING;
case APPROVED;
case REJECTED;
public function label(): string {
return match($this) {
Status::PENDING => 'Pending',
Status::APPROVED => 'Approved',
Status::REJECTED => 'Rejected',
};
}
}
$status = Status::PENDING;
echo $status->label(); // Pending
?>
13. Best practice e suggerimenti
Ecco alcune best practice essenziali di PHP:
<?php
// 1. Always use PHP opening tags
// Good: <?php
// Avoid: <? (short tags)
// 2. Use prepared statements for database queries
// Prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
// 3. Validate and sanitize input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
// 4. Use meaningful variable names
// Good:
$user_age = 25;
$is_active = true;
// Bad:
$a = 25;
$flag = true;
// 5. Handle errors gracefully
function divide($a, $b) {
if ($b == 0) {
throw new InvalidArgumentException("Division by zero");
}
return $a / $b;
}
// 6. Use type declarations (PHP 7+)
function calculateTotal(array $items): float {
return array_sum($items);
}
// 7. Organize code with namespaces
namespace App\Models;
class User {
// class implementation
}
// 8. Use composer for dependency management
// composer.json example:
/*
{
"require": {
"monolog/monolog": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
*/
?>
PHP è un linguaggio potente e flessibile perfetto per lo sviluppo web. Questo tutorial ha coperto i concetti essenziali di cui hai bisogno per iniziare a costruire applicazioni PHP. Pratica questi concetti, esplora framework PHP come Laravel o Symfony, e continua ad imparare!