首页 > 解决方案 > 是否可以从数组执行命令?

问题描述

只是出于好奇,是否可以执行以下操作:

$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

解决方案


以可重用且可以传递的方式存储“命令”的标准方法是使用函数

<?php

$commands = [
     function () { print 1+2; },
     function () { print 2+6; }
];

foreach ($commands as $command) {
    $command();
    print "\n";
}

推荐阅读