只是出于好奇是否可以做这样的事情:$commands = [ strtolower('JUST TESTING'), date('Y-m-d H:i:s'), strtoupper('Done!'),];foreach ($commands as $command) { $command;}这当然不行!有办法让它发挥作用吗?我的具体用例是这样的:private function dropDatabasesAndMySQLUsers(): void{ foreach ($this->getCommands() as $command) { $command; } $this->info('Done! All app Databases and MySQL users are dropped');}public function getCommands(): array{ return [ \DB::statement("DROP USER IF EXISTS 'myuser'@'localhost'"), \DB::statement("DROP DATABASE IF EXISTS manager") // I have about 20-30 of these ];}
2 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
以可重用且可传递的方式存储“命令”的标准方法是使用函数。
<?php
$commands = [
function () { print 1+2; },
function () { print 2+6; }
];
foreach ($commands as $command) {
$command();
print "\n";
}
慕娘9325324
TA贡献1783条经验 获得超4个赞
实现此目的的另一种方法是将函数名称用作字符串。"strtolower"("FOO");将提供与以下相同的输出strtolower("FOO");:
<?php
$commands = [
"strtolower" => 'JUST TESTING',
"date" => 'Y-m-d H:i:s',
"strtoupper" => 'Done!',
];
foreach ($commands as $functionName => $arg) {
echo $functionName($arg) . PHP_EOL;
}
这输出:
just testing
2020-07-04 14:45:16
DONE!
- 2 回答
- 0 关注
- 130 浏览
添加回答
举报
0/150
提交
取消