Search code examples
phptwilio

Using a PHP use keyword conditionally Twilio Programmable SMS


Looked around and can't really find an answer.

I have a web app that is sending SMS messages using the Twilio SDK

Some installs have Twilio installed and some do not.

I want this code to run only if the Twilio files exist.

The regular code is:

require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
use Twilio\Rest\Client;

I have tried

if(file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
    require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';

    use Twilio\Rest\Client;
}

and also

if(file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
    require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
}
if(class_exists(Twilio\Rest\Client)) {
    use Twilio\Rest\Client;
}



if(file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
    require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';

}

use Twilio\Rest\Client;

and always get

syntax error, unexpected 'use'

Is there a way to make this conditional?


Solution

  • Why not use use unconditionally?

     <?php
     use Twilio\Rest\Client;
    
     if (is_file(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
          require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
     }
    

    I can run this code without any issue.

    Probably risking name conflicts with Twilio\Rest\Client but I think you'd have this either way.