# Referência Rápida de PHP

*Sintaxe, arrays, OOP, banco de dados, E/S de arquivos*

> Source: PHP Manual (php.net) · MIT

## Básico

### Hello World

```
<?php
echo "Hello, World!\n";
// PHP code must be inside <?php ... ?> tags
```

### Executar PHP

```
php script.php          # run a file
php -r 'echo "hi\n";'  # run inline code
php -S localhost:8000   # built-in dev server
```

### Comentários

```
// single-line comment
# also single-line
/* multi-line
   comment */
```

## Variáveis e Tipos

### Variáveis

```
$name = "PHP";          // string
$version = 8.3;         // float
$count = 42;            // int
$active = true;         // bool
$items = null;          // null
```

### Verificação de Tipo

| Command | Description |
|---------|-------------|
| `gettype($x)` | Retorna o tipo como string |
| `is_string($x)` | Verificar se é string |
| `is_int($x)` | Verificar se é inteiro |
| `is_array($x)` | Verificar se é array |
| `is_null($x)` | Verificar se é nulo |
| `isset($x)` | Verificar se está definido e não é nulo |
| `empty($x)` | Verificar se é vazio (falsy) |

### Conversão de Tipo

```
$n = (int) "42";       // 42
$s = (string) 3.14;    // "3.14"
$b = (bool) "";        // false
$a = (array) $obj;     // object to array
```

### Constantes

```
define("MAX_SIZE", 100);
const API_VERSION = "v2";
echo MAX_SIZE;   // 100
```

## Strings

### Noções Básicas de Strings

```
$name = "World";
echo "Hello, $name!";         // variable interpolation
echo 'Hello, $name!';         // literal (no interpolation)
echo "Value: {$arr['key']}";  // complex expression
```

### Funções de String

| Command | Description |
|---------|-------------|
| `strlen($s)` | Comprimento em bytes |
| `mb_strlen($s)` | Comprimento em caracteres (seguro para multibyte) |
| `strtolower($s)` | Converter para minúsculas |
| `strtoupper($s)` | Converter para maiúsculas |
| `trim($s)` | Remover espaços das extremidades |
| `str_replace(a, b, $s)` | Substituir `a` por `b` em `$s` |
| `substr($s, 0, 5)` | Substring da posição 0, comprimento 5 |
| `strpos($s, 'find')` | Encontrar posição de substring (false se não encontrado) |
| `explode(',', $s)` | Dividir string em array |
| `implode(',', $a)` | Juntar array em string |

### Heredoc e Nowdoc

```
$html = <<<HTML
<p>Hello, $name</p>
HTML;
$raw = <<<'TEXT'
No $interpolation here
TEXT;
```

## Arrays

### Indexados e Associativos

```
$nums = [1, 2, 3];                 // indexed
$user = ["name" => "Alice", "age" => 30];  // associative
$nums[] = 4;                        // append
echo $user["name"];                 // access
```

### Funções de Array

| Command | Description |
|---------|-------------|
| `count($a)` | Número de elementos |
| `array_push($a, $v)` | Acrescentar ao final |
| `array_pop($a)` | Remover e retornar o último elemento |
| `array_merge($a, $b)` | Mesclar dois arrays |
| `in_array($v, $a)` | Verificar se valor existe |
| `array_key_exists($k, $a)` | Verificar se chave existe |
| `array_map($fn, $a)` | Aplicar função a cada elemento |
| `array_filter($a, $fn)` | Filtrar elementos por callback |
| `sort($a)` | Ordenar no lugar (reindexar) |
| `array_keys($a)` | Retornar todas as chaves |

### Iteração

```
foreach ($users as $user) { echo $user; }
foreach ($map as $key => $value) {
    echo "$key: $value\n";
}
```

## Funções

### Função Básica

```
function add(int $a, int $b): int {
    return $a + $b;
}
echo add(3, 5);
```

### Argumentos Padrão e Nomeados

```
function greet(string $name, string $greeting = "Hello"): string {
    return "$greeting, $name!";
}
greet("Alice");
greet(greeting: "Hi", name: "Bob");  // named args (PHP 8+)
```

### Arrow Functions

```
$double = fn(int $x): int => $x * 2;
$nums = array_map(fn($n) => $n * 10, [1, 2, 3]);
```

### Closures

```
$factor = 3;
$multiply = function(int $x) use ($factor): int {
    return $x * $factor;
};
echo $multiply(5);   // 15
```

## Classes e Objetos

### Definição de Classe

```
class User {
    public function __construct(
        private string $name,
        private int $age = 0,
    ) {}
    public function greet(): string { return "Hi, {$this->name}"; }
}
```

### Herança e Interfaces

```
interface Printable {
    public function toString(): string;
}
class Admin extends User implements Printable {
    public function toString(): string { return "Admin"; }
}
```

### Visibilidade

| Command | Description |
|---------|-------------|
| `public` | Acessível de qualquer lugar |
| `protected` | Acessível da classe e subclasses |
| `private` | Acessível apenas dentro da classe |
| `readonly` | Pode ser atribuído apenas uma vez (PHP 8.1+) |
| `static` | Pertence à classe, não às instâncias |
| `abstract` | Deve ser implementado pela subclasse |

### Traits

```
trait Timestamped {
    public function createdAt(): string {
        return date('Y-m-d H:i:s');
    }
}
class Post { use Timestamped; }
```

## Tratamento de Erros

### Try / Catch / Finally

```
try {
    $result = riskyOperation();
} catch (InvalidArgumentException $e) {
    echo "Bad input: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally { cleanup(); }
```

### Exceções Personalizadas

```
class ApiException extends RuntimeException {
    public function __construct(string $message, private int $statusCode = 500) {
        parent::__construct($message, $statusCode);
    }
}
```

### Segurança Nula (PHP 8+)

```
$len = $user?->address?->zip;  // nullsafe operator
$name = $input ?? "default";   // null coalescing
$data ??= [];                  // null coalescing assignment
```

## E/S de Arquivos

### Ler e Escrever Arquivos

```
$content = file_get_contents("data.txt");
file_put_contents("out.txt", $content);
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
```

### Handle de Arquivo

```
$f = fopen("log.txt", "a");
fwrite($f, "entry\n");
fclose($f);
```

### Funções de Arquivo

| Command | Description |
|---------|-------------|
| `file_exists($path)` | Verificar se arquivo existe |
| `is_dir($path)` | Verificar se é diretório |
| `mkdir($path, 0755, true)` | Criar diretório recursivamente |
| `unlink($path)` | Excluir um arquivo |
| `glob('*.txt')` | Encontrar arquivos por padrão |
| `realpath($path)` | Resolver caminho absoluto completo |

## Banco de Dados

### Conexão PDO

```
$pdo = new PDO(
    "mysql:host=localhost;dbname=app",
    "user", "password",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
```

### Prepared Statements

```
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([":id" => 42]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
```

### Inserção e Atualização

```
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["Alice", "alice@example.com"]);
$id = $pdo->lastInsertId();
```

### Modos de Fetch do PDO

| Command | Description |
|---------|-------------|
| `fetch()` | Buscar uma linha |
| `fetchAll()` | Buscar todas as linhas |
| `FETCH_ASSOC` | Retornar como array associativo |
| `FETCH_OBJ` | Retornar como objeto anônimo |
| `FETCH_CLASS` | Retornar como instância da classe especificada |

## Funções Comuns

### JSON

```
$json = json_encode(["name" => "Alice", "age" => 30]);
$data = json_decode($json, true);  // true = assoc array
$data = json_decode($json);        // object
```

### Data e Hora

```
echo date("Y-m-d H:i:s");           // 2026-03-26 12:00:00
$ts = strtotime("+1 week");
$dt = new DateTime("2026-01-01");
echo $dt->format("D, M j");          // Thu, Jan 1
```

### Matemática e Aleatório

| Command | Description |
|---------|-------------|
| `abs($n)` | Valor absoluto |
| `round($n, 2)` | Arredondar para 2 casas decimais |
| `ceil($n) / floor($n)` | Arredondar para cima / para baixo |
| `min($a, $b) / max($a, $b)` | Mínimo / máximo |
| `random_int(1, 100)` | Inteiro aleatório criptograficamente seguro |
| `number_format($n, 2)` | Formatar com separador de milhares |

### Expressões Regulares

```
preg_match('/^[a-z]+$/i', $str, $matches);
preg_match_all('/\d+/', $str, $all);
$result = preg_replace('/\s+/', ' ', $str);
```
