skip to Main Content

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 TwilioRestClient;

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 TwilioRestClient;
}

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(TwilioRestClient)) {
    use TwilioRestClient;
}



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

}

use TwilioRestClient;

and always get

syntax error, unexpected ‘use’

Is there a way to make this conditional?

2

Answers


  1. Chosen as BEST ANSWER

    Thank you marco-a

    Ended up using

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

    Still not sure why putting the use statement before works, but it does lol


  2. Why not use use unconditionally?

     <?php
     use TwilioRestClient;
    
     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 TwilioRestClient but I think you’d have this either way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search