PHP 8.  :     production
 


           .        PHP 8:          Nginx, PostgreSQL  HTTPS.

  ,    :     HTML       , DI-,    .   ,   ,  ,    .       Laravel  Symfony  ,  .

        .     HTTP  ,  ,   XSS  CSRF,  CI  .     .

 ,      PHP        .





PHP 8.  :     production





 1.    PHP




    ,      ,    .

1.1.    



  ,    PHP,      .     :



   WordPress-.



   HTML   SQL,    2005 .



     . (,   .)



    . PHP   1994    CGI-    .        .    ,       (strpos vs str_rot13)    :  PHP  Wikipedia, Facebook (), Slack    .



      . PHP    :



PHP 7 (2015):   ,    .



PHP 8 (2020...):  , , match-, readonly-  JIT-.



 PHP       .     , ,    ,   Composer.   PHP 8    ,  ,       Kotlin  TypeScript.



: PHP    .

:  PHP   API, ,      .     PHPStan  Psalm      Python  Node.js.



     PHP,   .  ,     -.

1.2.   



  IDE   .   :



PHP 8.2  8.3.     ,       Docker.



 . VS Code   Intelephense   . PhpStorm        .



Composer.  .    ,    .



   Docker (,   ):



       docker-compose.yml:

yaml



version: '3.8'

services:

app:

image: php:8.3-cli

volumes:

- .:/app

working_dir: /app



: docker compose run --rm app php script.php.

. PHP ,      .



 ,     Docker:    php.net   php -S localhost:8000 ( -)    .

1.3.  .  Hello, World,    



 hello world .   ,    PHP:

php



<?php



declare(strict_types=1);



function greet(string $name, ?string $title = null): string

{

$prefix = $title ?? '';

return ", {$prefix} {$name}!";

}



echo greet('', ''); // ,  !

echo greet('');                // ,  !



    :



declare(strict_types=1)         . PHP      "123abc"  123    ,  int.   ,   .    ,   .



  greet(string $name, ?string $title = null): string         . ?string    null.       . PHP     .   int  string       TypeError,      .



 ?? (null coalescing)        null,  .  isset($title) ? $title : ''.



     ,     ,      HTML.



1.4.  PHP   ( )



PHP       .    PHP  .    :



   OPcache (-)    .      .



  PHP 8.0,    JIT-,          .      (    PHP   ,         ).



     ,  : PHP    -.  ,       -.      Swoole  RoadRunner       ,     .

1.5.    ( )



       -.        .     :



 2-4:  ,    .



 5-8:  , , API     .



 9-12:    (DI,  , ).



 13-15: Composer,      .



    . ,        :



:  PHP,     ,       ,   TypeError. ,       ,          NaN?.

  :






 2.     




   ,  mixed   ,  union types   ,   PHP     ,     .

2.1.   ,  PHP ?



PHP      .  $x   ,  ,    DatabaseConnection,    .  ,        .



      ,    :

php



// .   .

function calculateDiscount(float $price, int $percent): float

{

return $price * ($percent / 100);

}



calculateDiscount('100', ''); //  ?

// PHP   '100'  100.0,  ''  0.

// : 0.0.  ,  .    .



 strict_types=1    TypeError     .       . PHP   .



:        .   ,      ,    ,     .

2.2.     



 : int, float, string, bool.  ,   .    .



int  float

php



declare(strict_types=1);



function divide(int $a, int $b): float

{

return $a / $b;

}



echo divide(5, 2); // 2.5

//  float   .



//    :

function getInt(): int

{

return 5.7; // TypeError: Return value must be of type int, float returned.

}



PHP   5.7  6  ,    ,   .    .



bool:    -

php



function isActive(bool $status): string

{

return $status ? '' : '';

}



isActive(1);     // TypeError. 1   bool.

isActive('true');// TypeError. 'true'   bool.



 true  false.  0, 1, 'yes'.  ,   .



string:   null

php



function sayHello(string $name): string

{

return "Hello, {$name}";

}



sayHello(null); // TypeError  ?string.



    null,       (    ).

2.3. Union Types:    



 PHP 8.0  ,      . : A|B.

php



function formatBalance(int|float $amount): string

{

return number_format($amount, 2, '.', ' ') . ' ';

}



formatBalance(1500);   // "1 500.00 "

formatBalance(99.5);   // "99.50 "

formatBalance('100');  // TypeError: string is not int|float.



 PHP 8.0           mixed   . Union types   ,     .



 :   null

php



function findUser(int $id): ?User

{

//  User  null,   .

}



?User     User|null.   ,  ?Type     . : ?int $x = null     null ,  PHP    .

2.4. Mixed:  



mixed  ,  :       ,   .   ,   .

php



function logAnything(mixed $data): void

{

file_put_contents('app.log', print_r($data, true), FILE_APPEND);

}



logAnything(['user' => 'admin']);

logAnything('- ');

logAnything(42);

logAnything(new Exception(''));



  mixed:



  -.



,      (, ).



    .



  :



  -.   createOrder  mixed, -   .



2.5.  : void, never  static



void



    (,  null,  PHP    null):

php



function sendEmail(string $to): void

{

//    .

// return null;  .

// return;       .

}



never



   PHP 8.1.       .    ,   exit().

php



function redirect(string $url): never

{

header("Location: {$url}");

exit();

}



function throwNotFound(): never

{

throw new \RuntimeException(' ');

}



  ?    never  :      .   :

php



$user = findUser($id) ?? throwNotFound();

//  $user   null. PHPStan  .



static



  .    static, ,     ,   ,   ,   .

php



class QueryBuilder

{

public function where(string $clause): static

{

//     .

return $this;

}

}



class UserQuery extends QueryBuilder

{

public function active(): static

{

return $this->where('active = 1');

}

}



$query = (new UserQuery())->active();

// $query   UserQuery,  QueryBuilder.



     (fluent API)     IDE.

2.6.   



 PHP 7.4      .  PHP 8.1    readonly.

php



class Money

{

public readonly float $amount;

public readonly string $currency;



public function __construct(float $amount, string $currency)

{

$this->amount = $amount;

$this->currency = $currency;

}

}



$m = new Money(100.0, 'RUB');

$m->amount = 200.0; // Error: Cannot modify readonly property.



:



readonly      (  ).



        .



           .



2.7.  : instanceof   



 :

php



if ($user instanceof Admin) {

//   .

}



     instanceof .     ,    ( 4  ).



 :    User|null,      :

php



$user = $repository->find($id);

if ($user === null) {

throw new \RuntimeException('  ');

}

//  $user   User.



  (PHP 8.0+):

php



$user = $repository->find($id) ?? throw new \RuntimeException(' ');



 ?? + throw  ,     if.

2.8.  



  calculateTotal(array $items, float $discount = 0.0): float.



$items    (float).



$discount    .



 strict_types=1.



    .



   ,    float,   TypeError.



  transfer(Money $from, Money $to, int|float $amount): void.



,  $amount  .



  $from  $to     .



  Temperature  readonly- float $celsius   toFahrenheit(): float.        .  .






 3. ,   ,  




     switch  ,       ,  array_map      .

3.1.  : 



   PHP  .     PHP 8  ,    .



  (PHP 8.0)



    .      :

php



function createInvoice(

string $client,

float $amount,

string $currency = 'RUB',

bool $paid = false,

): string {

// ...

}



//  :

createInvoice(

client: ' ',

amount: 15000.00,

paid: true,

);



//    (    ):

createInvoice(

paid: false,

amount: 5000.00,

client: ' ',

);



:



 .



     ,       .



        string-    .



 : ...$args



       :

php



function sum(int ...$numbers): int

{

return array_sum($numbers);

}



sum(1, 2, 3, 4); // 10

sum();           // 0



//    TypeError:

sum(1, '', 3);



     :

php



$data = [1, 2, 3];

sum(...$data); // 6



Callback-: callable



    :

php



function applyDiscount(array $prices, callable $discountFn): array

{

return array_map($discountFn, $prices);

}



applyDiscount([100, 200], fn(float $p) => $p * 0.9);

// [90.0, 180.0]



callable     ,   [$object, 'method'],    .       : \Closure.

3.2.    



      .              .

php



$multiplier = 2.5;



$fn = function (float $value) use ($multiplier): float {

return $value * $multiplier;

};



$fn(10); // 25.0



use       .   :

php



$x = 1;

$fn = function () use ($x): int {

return $x;

};



$x = 99;

echo $fn(); // 1,  99!



      use (&$x).    :        .      ,    .



  



     :

php



function makeMultiplier(float $factor): \Closure

{

return fn(float $value): float => $value * $factor;

}



$double = makeMultiplier(2);

$triple = makeMultiplier(3);



$double(5); // 10

$triple(5); // 15



  fn() => ...     . use  .    .

3.3.  :   



 PHP 7.4   :

php



// :

$fn = function (int $x) use ($y): int {

return $x + $y;

};



// :

$fn = fn(int $x): int => $x + $y;



  :



   ( ,  return).



   .



       { }.       .



 :  array_map, array_filter, usort   ,      .

php



$users = [

['name' => '', 'age' => 28],

['name' => '', 'age' => 35],

];



$names = array_map(fn(array $u): string => $u['name'], $users);

// ['', '']



$adults = array_filter($users, fn(array $u): bool => $u['age'] >= 30);

//  .



3.4. match-:  switch



switch    :  break    . match (PHP 8.0)  :

php



function getStatusText(int $code): string

{

return match($code) {

200 => 'OK',

301 => 'Moved Permanently',

404 => 'Not Found',

500 => 'Internal Server Error',

default => 'Unknown',

};

}



 :



  (===). match('200')    200.



,         default.



     (   =>      ).



 ,    return.



   :

php



function classifyNumber(int $n): string

{

return match(true) {

$n < 0   => '',

$n === 0 => '',

$n < 10  => '',

$n < 100 => '',

default  => '',

};

}



 match(true)    ,      .

3.5.     



    ,      .    makeMultiplier().   :



  ():

php



$formatPrice = fn(float $amount): string => number_format($amount, 2) . ' ';

$applyTax = fn(float $amount): float => $amount * 1.2;

$roundUp = fn(float $amount): float => ceil($amount);



// :      

$process = fn(float $a): string => $formatPrice($applyTax($roundUp($a)));



$process(99.1); // "119.00 "



   .       -,    .    :     ,   .



  ():

php



function discount(float $percent): \Closure

{

return fn(float $price): float => $price * (1 - $percent / 100);

}



$winterSale = discount(20);

$vipSale = discount(50);



$winterSale(1000); // 800.0

$vipSale(1000);    // 500.0



3.6.  :   



 :



             .



    (   ,    ,    ).



php



// :

function applyDiscountUnclean(float $price): float

{

global $currentUser;

if ($currentUser->isVip()) {

return $price * 0.8;

}

return $price;

}



// :

function applyDiscountPure(float $price, User $user): float

{

if ($user->isVip()) {

return $price * 0.8;

}

return $price;

}



:    .    ,   .    User   .



        ,  -  ,     (, , HTTP)     .     .

3.7.  



   :

  makeConverter(float $rate): \Closure,        .   $usdToRub  $eurToRub.  100   .



  match:

 calculate(float $a, float $b, string $operation): float|string. : '+', '-', '*', '/'.       ':   '.  match.   ,  '+'  '+'    .



   :

  :

php



$users = [

['name' => '', 'age' => 25],

['name' => '', 'age' => 31],

['name' => 'ϸ', 'age' => 19],

];



        usort   .      .     print_r.



   :

     :

php



function addTransaction(float $amount, string $category): void

{

global $transactions;

$transactions[] = ['amount' => $amount, 'category' => $category];

}



 ,     global,      . ,     .






 4.   




       ,   enum  readonly,  ,       .

4.1.     PHP?



PHP   .     PHP 4 (),   PHP 5 (),          .



    ,      ? :  .



,     float $amount  string $currency.     : ['amount' => 100, 'currency' => 'RUB'].  ,  -  'RUB'  'rub'  'RUR'? ,  amount  ?



    :  .  ,   .     .

php



class Money

{

public function __construct(

public readonly float $amount,

public readonly string $currency,

) {

if ($amount < 0) {

throw new \InvalidArgumentException('    ');

}

if (!in_array($currency, ['RUB', 'USD', 'EUR'], true)) {

throw new \InvalidArgumentException(" : {$currency}");

}

}

}



$m = new Money(100.0, 'RUB'); // .

$m = new Money(-50.0, 'RUB'); // .

$m = new Money(50.0, 'RUR');  // .



 ,   Money,  :  ,  .    .        private   ,   .

4.2.    PHP 8



 PHP 8.0    :

php



//  (PHP 7):

class User

{

private string $name;

private int $age;



public function __construct(string $name, int $age)

{

$this->name = $name;

$this->age = $age;

}

}



//  (PHP 8):

class User

{

public function __construct(

private string $name,

private int $age,

) {}

}



  (public, private, protected)       ,  .  .



 readonly (PHP 8.1)   :

php



class User

{

public function __construct(

public readonly string $name,

public readonly int $age,

) {}

}



 $name  $age    ,     .   DTO  value objects.

4.3. readonly- (PHP 8.2)



      readonly,    :

php



readonly class Money

{

public function __construct(

public float $amount,

public string $currency,

) {

//  .

}

}



   readonly.    .   static- (   ).     .



 :



Value objects (Money, Email, DateRange).



DTO     .



,      .



4.4. Enum:   



 PHP 8.1   :

php



class TransactionType

{

public const INCOME = 'income';

public const EXPENSE = 'expense';

}



function logTransaction(float $amount, string $type): void

{

// $type    . 'income'? 'Income'? 'iNcOmE'?

}



  enum:

php



enum TransactionType: string

{

case Income = 'income';

case Expense = 'expense';

}



 enum. TransactionType::Income   ,       'income'.       :

php



function logTransaction(float $amount, TransactionType $type): void

{

// $type   Income  Expense.  .

}



logTransaction(100.0, TransactionType::Income);



Enum'   :

php



enum TransactionType: string

{

case Income = 'income';

case Expense = 'expense';



public function label(): string

{

return match($this) {

self::Income => '',

self::Expense => '',

};

}



public function isIncome(): bool

{

return $this === self::Income;

}

}



TransactionType::Income->label(); // ''



 enum ( ):

php



enum Status

{

case Draft;

case Published;

case Archived;

}



 : string  : int.   .           .   , ,   .



 tryFrom  from:

php



$type = TransactionType::from('income');    // Income

$type = TransactionType::from('invalid');   // ValueError



$type = TransactionType::tryFrom('invalid'); // null ( )



4.5. : ,  



   :    X.   .

php



interface CalculatesArea

{

public function area(): float;

}



class Rectangle implements CalculatesArea

{

public function __construct(

private float $width,

private float $height,

) {}



public function area(): float

{

return $this->width * $this->height;

}

}



class Circle implements CalculatesArea

{

public function __construct(

private float $radius,

) {}



public function area(): float

{

return pi() * $this->radius ** 2;

}

}



function printArea(CalculatesArea $shape): void

{

echo ": " . $shape->area() . "\n";

}



printArea(new Rectangle(5, 3)); // 15

printArea(new Circle(2));       // ~12.57



 printArea       .    :     area(): float.    .

4.6.   



     .        .



  :

php



class Bird

{

public function fly(): string

{

return ' !';

}

}



class Penguin extends Bird

{

public function fly(): string

{

throw new \Exception('  !');

}

}



  ,    . ,  Bird,   Penguin.      (LSP).



  :

php



interface FlyBehavior

{

public function fly(): string;

}



class FlyWithWings implements FlyBehavior

{

public function fly(): string

{

return ' !';

}

}



class CantFly implements FlyBehavior

{

public function fly(): string

{

return '  .';

}

}



class Bird

{

public function __construct(

private readonly string $name,

private readonly FlyBehavior $flyBehavior,

) {}



public function tryToFly(): string

{

return "{$this->name}: " . $this->flyBehavior->fly();

}

}



$eagle = new Bird('', new FlyWithWings());

$penguin = new Bird('', new CantFly());



$eagle->tryToFly();   // :  !

$penguin->tryToFly(); // :   .



        .    ?   JetFly.    Bird,   .



    Dependency Injection ( 9),    .

4.7. : , 



      ,  . ,  .



 : Timestampable    createdAt  updatedAt  .

php



trait Timestampable

{

private \DateTimeImmutable $createdAt;

private ?\DateTimeImmutable $updatedAt = null;



public function initializeTimestamps(): void

{

$this->createdAt = new \DateTimeImmutable();

}



public function touch(): void

{

$this->updatedAt = new \DateTimeImmutable();

}



public function getCreatedAt(): \DateTimeImmutable

{

return $this->createdAt;

}



public function getUpdatedAt(): ?\DateTimeImmutable

{

return $this->updatedAt;

}

}



 : ,         :

php



trait BadTrait

{

public function doStuff(): void

{

$this->logger->log('- ...'); //  logger? .

}

}



  ,     $logger.    .    ,   .



:         ,    .   .

4.8.     



 ,  :

php



enum TransactionType: string

{

case Income = 'income';

case Expense = 'expense';



public function sign(): int

{

return match($this) {

self::Income => 1,

self::Expense => -1,

};

}

}



readonly class Money

{

public function __construct(

public float $amount,

public string $currency,

) {

if ($amount < 0) {

throw new \InvalidArgumentException('    ');

}

}



public function add(self $other): self

{

if ($this->currency !== $other->currency) {

throw new \InvalidArgumentException('  ');

}

return new self($this->amount + $other->amount, $this->currency);

}

}



readonly class Transaction

{

public function __construct(

public Money $money,

public TransactionType $type,

public string $category,

public \DateTimeImmutable $date,

) {}



public function signedAmount(): float

{

return $this->money->amount * $this->type->sign();

}

}



?



  Money   .



  Transaction   .



signedAmount()          .



 .       .



     .      ,   ,        ,  .

4.9.  



  :

   Money  subtract(Money $other): Money. ,    ,   ( ).   .



Enum  :

 enum Category: string  : Salary, Food, Transport, Entertainment, Other.   isEssential(): bool    (, )  true.



  :

  Shape   area(): float.   Square  Triangle,  .   totalArea(Shape ...$shapes): float,   .    .



  :

  NotificationChannel   send(string $message): void.  EmailChannel  SmsChannel.   Notifier,          notify(string $message)     .      .






 5.    




     SQLite  ,    SQL-   Repository,     .

5.1.   ORM?



ORM (Doctrine, Eloquent)   .     SQL  ,  ,     .    PDO   SQL, ORM   ,     ,    500  ,   .



     SQLite   ,         .     PostgreSQL  MySQL,  PDO-   .

5.2.   PDO



PDO (PHP Data Objects)         . :

php



//   ?     .

$dsn = 'sqlite:' . __DIR__ . '/database.sqlite';



$pdo = new PDO($dsn);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);



  :



ERRMODE_EXCEPTION    SQL   .   PDO   false,   ,   .



FETCH_ASSOC       .    .



DSN   sqlite:   MySQL   mysql:host=...;dbname=....



:

php



$pdo->exec('SELECT 1'); //      .



5.3.  :    SQL



   ,       4:

php



$pdo->exec('

CREATE TABLE IF NOT EXISTS transactions (

id INTEGER PRIMARY KEY AUTOINCREMENT,

amount REAL NOT NULL,

currency TEXT NOT NULL,

type TEXT NOT NULL,

category TEXT NOT NULL,

date TEXT NOT NULL,

created_at TEXT NOT NULL DEFAULT (datetime(\'now\'))

)

');



:



REAL   (SQLite   float  double).



TEXT      ISO 8601 (2026-03-15), PHP  .



type  currency   .       -   ,      enum-  PHP  (   ,   ).



created_at        .



  .  production-    Phinx  Doctrine Migrations,     .

5.4.  :   



SQL-         -.   '; DROP TABLE users; --   , ...

php



//    :

$name = $_GET['name'];

$sql = "SELECT * FROM users WHERE name = '{$name}'";

//  $name = "'; DROP TABLE users; --",  .



    :

php



$name = $_GET['name'];

$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');

$stmt->execute(['name' => $name]);

$user = $stmt->fetch();



PDO  SQL   .     ,           SQL-.   .



  vs :

php



//  ():

$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

$stmt->execute(['id' => $userId]);



//  (?):

$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');

$stmt->execute([$userId]);



        .



 :

php



$stmt = $pdo->prepare('

INSERT INTO transactions (amount, currency, type, category, date)

VALUES (:amount, :currency, :type, :category, :date)

');



$stmt->execute([

'amount' => 1500.00,

'currency' => 'RUB',

'type' => 'income',

'category' => '',

'date' => '2026-03-15',

]);



$newId = (int) $pdo->lastInsertId(); // ID  .




  .


   .

   ,     (https://www.litres.ru/pages/biblio_book/?art=74208439)  .

      Visa, MasterCard, Maestro,    ,   ,     ,  PayPal, WebMoney, ., QIWI ,       .


