php - 是否可以从数组执行命令?
问题描述
只是出于好奇,是否可以执行以下操作:
$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
];
}
解决方案
以可重用且可以传递的方式存储“命令”的标准方法是使用函数。
<?php
$commands = [
function () { print 1+2; },
function () { print 2+6; }
];
foreach ($commands as $command) {
$command();
print "\n";
}
推荐阅读
- java - 使用排名数组查找优先级队列的最小/最大元素
- sas - 我的 SAS 代码出现错误,我可以寻求帮助吗?
- c++ - 协程参数的生命周期是多少
- python - Python 使用 geopandas 绘制纬度和经度。Pryproj 异常
- python - 在python中组合数字和字符串列表
- terraform - 替代方式,因为 for_each 和 count 不能在同一资源中
- visual-studio - Xamarin 部署到 Android
- ios - Swift - 如何让 NSTimeZone 给我“太平洋标准时间”或“山地时间”等?
- angular - 在 Angular 中正确使用 ngClass
- vue.js - Vue.js - 组件渲染函数中的无限更新循环