BigJobbies BigJobbies - 1 month ago 6
PHP Question

PHP Calling dynamic functions

Im trying to figure out how to call functions based on what a user clicks on a form. But im not sure if im doing it right.

I have a number of classes, lets say 3 for different ways to connect to a site, the user clicks on which one they would like.


  1. FTP

  2. SFTP

  3. SSH



Which i have named 'service' in my code.

I don't want to run a whole bunch of IF statements, i would rather try and build the call dynamically.

What i have at the moment is as follows

$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;

$service = $request->input('service') . '_backup';
$service->testConn($request);


Im getting the following error

Call to a member function testConn() on string


Im not sure im doing this right.

Any help would be greatly appreciated.

Thanks

Answer

First of all $service is a string on which You cannot call method, because it is not an object (class instance).

I think it is a great example of where You can use Strategy Pattern which look like that:

class BackupStrategy {
    private $strategy = NULL; 

    public function __construct($service_name) {
        switch ($service_name) {
            case "ftp": 
                $this->strategy = new FTPBackup();
            break;
            case "sftp": 
                $this->strategy = new SFTPBackup();
            break;
            case "ssh": 
                $this->strategy = new SSHBackup();
            break;
        }
    }

    public function testConn() {
      return $this->strategy->testConn();
    }
}

And then in place where You want to call it You call it by:

$service = new BackupStrategy($request->input('service'));
$service->testConn($request);

I suggest You to read about Design Patterns in OOP - it will help You a lot in the future.