L'antisèche des interfaces PHP

Publié le 15/06/2021 • Actualisé le 15/06/2021


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons une interface typique PHP. J'y ai ajouté des commentaires avec ce qui est autorisé ou pas. Pour chaque cas, j'ai ajouté le message d'erreur correspondant. La version de référence de PHP pour ce snippet est la 7.4


<?php

declare(strict_types=1);

namespace App\Samples;

// use App\Controller\PaginationTrait; // cannot use traits inside interfaces ❌

use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * The PHP interfaces cheatsheet: PHP 7.4.
 */
interface MyHttpKernelInterface extends HttpKernelInterface // interfaces can extend other interfaces ✅
{
    // use PaginationTrait; // cannot use traits inside interfaces ❌
    /**
     * Error= "Compile Error: Cannot use traits inside of interfaces. PaginationTrait is used in App\Samples\MyHttpKernelInterface".
     */
    public const MY_CONST = '2'; // constants are allowed ✅

    // public const MAIN_REQUEST = false; // Throws an error if the constant is alteady delcared in the parent interface:
    /**
     * Error: "Compile Error: Cannot inherit previously-inherited or override constant MAIN_REQUEST from interface Symfony\Component\HttpKernel\HttpKernelInterface".
     */

    // public static $toto = 'foo'; // public static member not allowed ❌
    /**
     * Error : Compile Error: Interfaces may not include member variables.
     */

    // protected function writePrivateProtected(string $key, string $content): int; // private / protected method declaration NOT allowed ❌
    /**
     * Error: "Compile Error: Access type for interface method App\Samples\MyHttpKernelInterface::writePrivateProtected() must be omitted".
     */

    // public function handle(); // cannot change the signature of a method of an extended interface ❌

    /**
     * Error: "Compile Error:
     *  Declaration of App\Samples\MyHttpKernelInterface::handle($message, array $context = Array, int $myIntrefaceParam = 2)
     *  must be compatible with
     *  Symfony\Component\HttpKernel\HttpKernelInterface::handle(Symfony\Component\HttpFoundation\Request $request, int $type = self::MAIN_REQUEST, bool $catch = true).
     */
    public function write(string $key, string $content): int; // public method declaration allowed ✅

    public function exists(string $key): bool; // ✅

    // Interfaces cannot have body ❌
    /*
    public function bodyNotAllowed(string $key)
    {
    }
    */
    /*
     * Error: "Compile Error: Interface function App\Samples\MyHttpKernelInterface::bodyNotAllowed() cannot contain body"
     */
}

 Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !