猿问

是否可以从数组执行命令?

只是出于好奇是否可以做这样的事情:


$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

    ];

}


慕尼黑的夜晚无繁华
浏览 131回答 2
2回答

喵喵时光机

以可重用且可传递的方式存储“命令”的标准方法是使用函数。<?php$commands = [&nbsp; &nbsp; &nbsp;function () { print 1+2; },&nbsp; &nbsp; &nbsp;function () { print 2+6; }];foreach ($commands as $command) {&nbsp; &nbsp; $command();&nbsp; &nbsp; print "\n";}

慕娘9325324

实现此目的的另一种方法是将函数名称用作字符串。"strtolower"("FOO");将提供与以下相同的输出strtolower("FOO");:<?php$commands = [&nbsp; &nbsp; "strtolower"&nbsp; &nbsp; => 'JUST TESTING',&nbsp; &nbsp; "date"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; => 'Y-m-d H:i:s',&nbsp; &nbsp; "strtoupper"&nbsp; &nbsp; => 'Done!',];foreach ($commands as $functionName => $arg) {&nbsp; &nbsp; echo $functionName($arg) . PHP_EOL;}这输出:just testing2020-07-04 14:45:16DONE!
随时随地看视频慕课网APP
我要回答