VictorWesterlund / functionflags
尝试驯服PHP常量以用作函数/方法标志
1.1.0
2023-04-18 18:28 UTC
README
一个库,旨在使使用PHP常量作为函数/方法标志变得更容易。
可以通过调用FunctionFlags的静态方法来全局定义和检查标志。
use FunctionFlags/FunctionFlags // Define global flags for use anywhere for this runtime FunctionFlags::define([ "MY_FLAG", "OTHER_FLAG" ]); // Returns true if MY_FLAG is passed function foo(int $flags = null): bool { return FunctionFlags::isset(MY_FLAG); } foo(MY_FLAG); // true foo(OTHER_FLAG|MY_FLAG); // true foo(OTHER_FLAG); // false foo(); // false
也可以通过创建新的FunctionFlags实例来将标志限定在类级别。只有在此实例中定义的标志将被匹配
use FunctionFlags/FunctionFlags $flags1 = new FunctionFlags(["FOO", "BAR"]); $flags2 = new FunctionFlags(["BAR", "BIZ"]); // Returns true if FOO is passed and present in $flags1 function foo(int $flags = null): bool { return $flags2->isset(FOO); } foo(FOO); // true foo(FOO|BIZ); // true foo(BIZ); // false foo(); // false
安装
需要PHP 8.1或更高版本
- 安装composer包
composer require victorwesterlund/functionflags
- 将FunctionFlags包含到您的项目中
use FunctionFlags/FunctionFlags
- 定义一些标志(使用静态方法进行演示)
FunctionFlags::define([ "MY_FLAG", "OTHER_FLAG" ]);
- 添加一个接受标志的函数
// 1. If your function takes more than 1 argument. The "flags" variable MUST be the last. // 2. It's recommended to make your "flags" variable default to some value if empty to make flags optional. function foo($bar = null, int $flags = null): bool { return FunctionFlags::isset(MY_FLAG); }
- 在函数调用中使用标志
// Your function can now accept flags. One or many using the Union operator `|` foo("hello world", OTHER_FLAG|MY_FLAG);