PHP.nl

First class callable syntax

Eerste klasse callable syntaxis

De eerste klasse callable syntaxis is geïntroduceerd vanaf PHP 8.1.0, als een manier om te creëren van . Het vervangt de bestaande callable syntaxis met behulp van strings en arrays. Het voordeel van deze syntaxis is dat het toegankelijk is voor statische analyse en de scope gebruikt op het punt waar de callable wordt verkregen.
anonieme functies callable

De syntaxis wordt gebruikt om een object van callable te creëren. accepteert elke expressie die direct kan worden aangeroepen in de PHP grammatica:

CallableExpr(...)``Closure``CallableExprVoorbeeld: Eenvoudige eerste klasse callable syntaxis

<?php

class Foo {
   public function method() {}
   public static function staticmethod() {}
   public function __invoke() {}
}

$obj = new Foo();
$classStr = 'Foo';
$methodStr = 'method';
$staticmethodStr = 'staticmethod';


$f1 = strlen(...);
$f2 = $obj(...);  // aanroepbaar object
$f3 = $obj->method(...);
$f4 = $obj->$methodStr(...);
$f5 = Foo::staticmethod(...);
$f6 = $classStr::$staticmethodStr(...);

// traditionele callable met behulp van string, array
$f7 = 'strlen'(...);
$f8 = [$obj, 'method'](...);
$f9 = [Foo::class, 'staticmethod'](...);
?>

Opmerking: > De is onderdeel van de syntaxis, en geen omissie.
...

heeft dezelfde semantiek als . Dat wil zeggen, in tegenstelling tot callable met behulp van strings en arrays, respecteert de scope op het punt waar het is gemaakt:

CallableExpr(...)``Closure::fromCallable``CallableExpr(...)Voorbeeld: Scope vergelijking van en traditionele callable

<?php

class Foo {
    public function getPrivateMethod() {
        return [$this, 'privateMethod'];
    }

    private function privateMethod() {
        echo __METHOD__, "\n";
    }
}

$foo = new Foo;
$privateMethod = $foo->getPrivateMethod();
$privateMethod();
// Fatale fout: Aanroep van private methode Foo::privateMethod() vanuit globale scope
// Dit komt omdat de aanroep buiten Foo wordt uitgevoerd en de zichtbaarheid vanaf dit punt wordt gecontroleerd.

class Foo1 {
    public function getPrivateMethod() {
        // Gebruikt de scope waar de callable wordt verkregen.
        return $this->privateMethod(...); // identiek aan Closure::fromCallable([$this, 'privateMethod']);
    }

    private function privateMethod() {
        echo __METHOD__, "\n";
    }
}

$foo1 = new Foo1;
$privateMethod = $foo1->getPrivateMethod();
$privateMethod();  // Foo1::privateMethod
?>

Opmerking: > Objectcreatie met deze syntaxis (bijv. ) wordt niet ondersteund, omdat de syntaxis niet als een aanroep wordt beschouwd.
new Foo(...)``new Foo()

Opmerking: > De eerste klasse callable syntaxis kan niet worden gecombineerd met de . Beide onderstaande resulteren in een compileertijdfout:
nullsafe operator```php

method(...); $obj?->prop->method(...); ?>

Documentatie