Php 根据阵列配置选择方法

Php 根据阵列配置选择方法,php,Php,因此,我有以下导入记录方法(我已从该方法中删除了不需要的部分): 那么我就这样称呼它: public function import_offices(): array { return $this->import_records([ 'settings_key' => 'import_offices', 'path' => 'offices', ]); } 在if语句中调用sync\u profile和sync\u office

因此,我有以下导入记录方法(我已从该方法中删除了不需要的部分):

那么我就这样称呼它:

public function import_offices(): array
{
    return $this->import_records([
        'settings_key' => 'import_offices',
        'path' => 'offices',
    ]);
}

在if语句中调用
sync\u profile
sync\u office
方法是否比硬编码
$config['settings\u key']==='string'
更简洁?

您可以在php中使用string调用函数

foreach ($result->data as $record) {
    $this->{$config["settings_key"]}($record);
}
然后您的
$config
将如下所示

return $this->import_records([
        'settings_key' => 'sync_office', // change this to your method name
        'path' => 'offices',
]);

return $this->import_records([
        'settings_key' => 'sync_office', // change this to your method name
        'path' => 'offices',
]);