# 3. Funcoes & Classes & Estruturas

## Introdução

O PHP evoluiu de uma linguagem funcional simples para uma linguagem orientada a objetos (POO) madura. Ferramentas modernas e frameworks (Laravel, Symfony) dependem inteiramente dessas estruturas.

## Funções

Blocos de código reutilizáveis definidos com a palavra-chave `function`.

```php
function check_login($user, $pass) {
    if ($user == "admin" && $pass == "secret") {
        return true;
    }
    return false;
}

$acesso = check_login("admin", "secret");
```

* **Passagem por Referência:** Use `&` se quiser que a função altere a variável original.
* **Tipagem de Argumentos (PHP 7+):** `function soma(int $a, int $b): int { ... }`.

## Orientação a Objetos (Classes)

```php
class WebShell {
    public $password;
    private $allowed_ips = ["127.0.0.1"];

    public function __construct($pwd) {
        $this->password = $pwd;
    }

    public function execute($cmd) {
        if ($this->is_authorized()) {
            return shell_exec($cmd);
        }
        return "Não autorizado";
    }

    private function is_authorized() {
        return in_array($_SERVER['REMOTE_ADDR'], $this->allowed_ips);
    }
}

$shell = new WebShell("minhasenha123");
echo $shell->execute("whoami");
```

### Conceitos Chave

* **`public`:** Acessível de qualquer lugar.
* **`private`:** Acessível apenas dentro da classe.
* **`protected`:** Acessível pela classe e seus herdeiros.
* **`__construct`:** Método chamado automaticamente ao criar o objeto (`new`).
* **`$this`:** Referência ao objeto atual.

## Tratamento de Erros e Exceções

O PHP moderno usa `try`, `catch` e `finally` para lidar com falhas de forma elegante.

```php
try {
    $db = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
} catch (PDOException $e) {
    echo "Erro de conexão: " . $e->getMessage();
} finally {
    echo "Fim da tentativa.";
}
```

## Estruturas de Dados Importantes

### 1. PDO (PHP Data Objects)

A forma segura e recomendada de interagir com bancos de dados, pois suporta **Prepared Statements** (Defesa contra SQL Injection).

### 2. JSON

Integração nativa total.

* `json_encode($array)`: Converte array para string JSON.
* `json_decode($json, true)`: Converte string JSON para array associativo.

> No PHP, classes e funções são usadas frequentemente para criar "Facades" ou "Handlers" que gerenciam requisições. Analisar essas estruturas permite encontrar falhas de lógica de negócio em aplicações complexas.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/programacao-e-linguagens/php/3.-funcoes-and-classes-and-estruturas.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
