0

Just out of curiosity is it possible to do something like this:

$commands = [
    strtolower('JUST TESTING'),
    date('Y-m-d H:i:s'),
    strtoupper('Done!'),
];


foreach ($commands as $command) {
    $command;
}

This of course doesn't work! Is there a way to make it work?


My specific use case is something like this:

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
    ];
}
lewis4u
  • 14,256
  • 18
  • 107
  • 148
  • Please research more before asking so that Stack Overflow does not need to house redundant content. This is a mega-duplicate. – mickmackusa Jul 04 '20 at 22:10

2 Answers2

5

The standard way to store a "command" in a way that is reusable and can be passed around is to use a function.

<?php

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

foreach ($commands as $command) {
    $command();
    print "\n";
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Another way to achieve that is to use the functions names as string. "strtolower"("FOO"); will provide the same output than 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;
}

This outputs :

just testing
2020-07-04 14:45:16
DONE!
Cid
  • 14,968
  • 4
  • 30
  • 45