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
    ];
}
1
  • Please research more before asking so that Stack Overflow does not need to house redundant content. This is a mega-duplicate. Commented Jul 4, 2020 at 22:10

2 Answers 2

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";
}
Sign up to request clarification or add additional context in comments.

Comments

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!

8 Comments

I needed this for functions like this \DB::statement("DROP USER IF EXISTS 'myuser'@'localhost'"); \DB::statement("DROP DATABASE IF EXISTS manager"); and I have about 20-30 of them so your solution is not appropriate for my case!
@lewis4u \DB::$functionName() works too
try to update your answer and add that to it... for others to see how would that look like with those 2 commands in my comment...
Update your question if you have a specific use case
Then store only the arguments in an array, loop over it and call \DB::statement($arg)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.