W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
從 PHP 8.1.0 開始引入第一類可調用語法,作為從可調用創(chuàng)建匿名函數(shù)的一種方法。它取代了使用字符串和數(shù)組的現(xiàn)有可調用語法。這種語法的優(yōu)點是可以進行靜態(tài)分析,并使用獲取可調用對象時的作用域。
CallableExpr(...) 語法用于從可調用對象創(chuàng)建閉包對象。 CallableExpr 接受任何可以在 PHP 語法中直接調用的表達式:
示例 #1 Simple first class callable syntax
<?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(...); // invokable object
$f3 = $obj->method(...);
$f4 = $obj->$methodStr(...);
$f5 = Foo::staticmethod(...);
$f6 = $classStr::$staticmethodStr(...);
// traditional callable using string, array
$f7 = 'strlen'(...);
$f8 = [$obj, 'method'](...);
$f9 = [Foo::class, 'staticmethod'](...);
?>
注意:The ... is part of the syntax, and not an omission.
CallableExpr(...) has the same semantics as Closure::fromCallable(). That is, unlike callable using strings and arrays, CallableExpr(...) respects the scope at the point where it is created:
示例 #2 Scope comparison of CallableExpr(...) and traditional callable
<?php
class Foo {
public function getPrivateMethod() {
return [$this, 'privateMethod'];
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo = new Foo;
$privateMethod = $foo->getPrivateMethod();
$privateMethod();
// Fatal error: Call to private method Foo::privateMethod() from global scope
// This is because call is performed outside from Foo and visibility will be checked from this point.
class Foo1 {
public function getPrivateMethod() {
// Uses the scope where the callable is acquired.
return $this->privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']);
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo1 = new Foo1;
$privateMethod = $foo1->getPrivateMethod();
$privateMethod(); // Foo1::privateMethod
?>
注意:Object creation by this syntax (e.g new Foo(...)) is not supported, because new Foo() syntax is not considered a call.
注意:The first-class callable syntax cannot be combined with the nullsafe operator. Both of the following result in a compile-time error: method(...);$obj?->prop->method(...);?>
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: