Categories

Safe Function Call

Author: Scott Reilly
Version: 1.3.1
First released: 2009-06-11
Last update: 2021-09-27
Compatibility: WP 1.5 – 5.8.7
Download: [ zip ]
Description:

Safely and easily call functions that may not be available (such as those provided by a plugin that gets deactivated)

Extended Description

Safely call a function, class method, or object method in a manner that doesn’t generate errors if those plugins cease to exist.

Various helper functions are provided that provide handy variations of this theme:

  • _sfc(): Safely call a function and get its return value
  • _sfce(): Safely call a function and echo its return value
  • _sfcf(): Safely call a function; if it doesn’t exist, then a fallback function (if specified) is called
  • _sfcm(): Safely call a function; if it doesn’t exist, then echo a message (if provided)

Let’s assume you had something like this in a template:

<?php list_cities( 'Texas', 3 ); ?>

If you deactivated the plugin that provided list_cities(), your site would generate an error when that template is accessed.

You can instead use _sfc(), which is provided by this plugin to call other functions, like so:

<?php _sfc( 'list_cities', 'Texas', 3 ); ?>

That will simply do nothing if the list_cities() function is not available.

If you’d rather display a message when the function does not exist, use _sfcm() instead, like so:

<?php _sfcm( 'list_cities', 'The cities listing is temporarily disabled.', 'Texas', 3 ); ?>

In this case, if list_cities() is not available, the text “The cities listing is temporarily disabled.” will be displayed.

If you’d rather call another function when the function does not exist, use _sfcf() instead, like so:

<?php
    function unavailable_function_handler( $function_name ) { echo "The function $function_name is not available."; }
    _sfcf( 'nonexistent_function', 'unavailable_function_handler' );
?>

In the event you want to safely call a function and echo its value, you can use _sfce() like so:

<?php _sfce( 'largest_city', 'Tx' ); ?>

Which is roughly equivalent to doing :

<?php if function_exists( 'largest_city' ) { echo largest_city( 'Tx' ); } ?>

Filter invocation method

To further prevent issues in your code should this plugin itself become deactivated, you can use indirect filter invocation to call the plugin functions. Each function has an associated filter with the same name as the function. Simply use apply_filters() to invoke that function instead of calling the function directly.

E.g. instead of:

<?php _sfce( 'some_plugin_function_that_echoes', 'argument' ); ?>

Do:

<?php apply_filters( '_sfce', 'some_plugin_function_that_echoes', 'argument' ); ?>

If you’re relying on the return value of a function and this plugin gets deactivated, note that the apply_filters() call will return the name of the function you intended to call, so you should check the return value to ensure the function got called.

Instead of:

<?php $x = _sfc( 'some_plugin_function', 'argument' ); ?>

Do:

<?php
    $x = apply_filters( '_sfcq', 'some_plugin_function', 'argument' );
    if ( $x !== 'some_plugin_function' ) {
        // Work with the value of $x here.
    } else {
        // The Safe Function Call plugin isn't active.
        $x = 0; // Maybe set the variable to something that makes sense in this scenario.
    }
?>

Links: Plugin Homepage | Plugin Directory Page | GitHub | Author Homepage

Template Tags

The plugin provides four functions for your use. Note: These functions are not limited to use in templates

Functions

  • <?php function _sfc($callback) ?>
    This will safely invoke the specified callback. You can specify an arbitrary number of additional arguments that will get passed to it. If the callback does not exist, nothing is displayed and no error is generated.

  • <?php function _sfce($callback) ?>
    The same as _sfc() except that it echoes the return value of the callback before returning that value.

  • <?php function _sfcf($callback, $fallback_callback = '') ?>
    The same as _sfc() except that it invokes the fallback callback (if it exists) if the callback does not exist. $function_name_if_missing() is sent $function_name as its first argument, and then subsequently all arguments that would have otherwise been sent to $function_name().

  • <?php function _sfcm($callback, $message_if_missing = '') ?>
    The same as _sfc() except that it displays a message (the value of $message_if_missing), if the callback does not exist.

Arguments

  • $callback
    A string representing the name of the function to be called, or an array of a class or object and its method (as can be done for add_action()/add_filter())

  • $message_if_missing
    (For _sfcm() only.) The message to be displayed if $function_name() does not exist as a function.

  • $fallback_callback
    (For _sfcf() only.) The function to be called if the callback does not exist.

Examples

  • <?php _sfc('list_cities', 'Texas', 3); /* Assuming list_cities() is a valid function */ ?>
    “Austin, Dallas, Fort Worth”

  • <?php _sfc(array('Cities', 'list_cities'), 'Texas', 3); /* Assuming list_cities() is a valid function in the 'Cities' class */ ?>
    “Austin, Dallas, Fort Worth”

  • <?php _sfc(array($obj, 'list_cities'), 'Texas', 3); /* Assuming list_cities() is a valid function in the object $obj */ ?>
    “Austin, Dallas, Fort Worth”

  • <?php _sfc('list_cities', 'Texas', 3); /* Assuming list_cities() is not a valid function */ ?>
    “”

  • <?php _sfcm('list_cities', 'Texas', 'Unable to list cities at the moment', 3); /* Assuming list_cities() is a valid function */ ?>
    “Austin, Dallas, Fort Worth”

  • <?php _sfcm('list_cities', 'Texas', 'Unable to list cities at the moment', 3); /* Assuming list_cities() is not a valid function */ ?>
    “Unable to list cities at the moment”

  • <?php _sfce('largest_city', 'Tx'); /* Assuming largest_city() is a valid function that does not echo/display its return value */ ?>
    “Houston”

  • <?php
    function unavailable_function_handler( $callback ) {
    echo "Sorry, but the function {$callback}() does not exist.";
    }
    _sfcf('nonexistent_function', 'unavailable_function_handler');
    ?>

Find out more at the plugin’s WordPress Plugin Repository page.

Installation

  1. Install via the built-in WordPress plugin installer. Or download and unzip safe-function-call.zip inside the plugins directory for your site (typically wp-content/plugins/)
  2. Activate the plugin through the ‘Plugins’ admin menu in WordPress
  3. Use any of the four functions provided by this plugin as desired

Release Log

1.3.1 (2021-09-26)

  • Change: Note compatibility through WP 5.8+
  • Unit tests:
    • Change: Restructure unit test directories
      • Change: Move phpunit/bin/ into tests/
      • Change: Move phpunit/ into tests/
    • Change: Remove ‘test-‘ prefix from unit test file
    • Change: In bootstrap, store path to plugin file constant
    • Change: In bootstrap, add backcompat for PHPUnit pre-v6.0

1.3 (2021-04-17)

  • This minor release adds support for a safer method of invoking the plugin’s own functions in a way that safeguards your usage against errors if the plugin gets deactivated and also notes compatibility through WP 5.7+.

Details:

  • New: Support filter invocation for all functions
    • Add filter _sfc to support filter invocation method _sfc()
    • Add filter _sfce to support filter invocation method _sfce()
    • Add filter _sfcf to support filter invocation method _sfcf()
    • Add filter _sfcm to support filter invocation method _sfcm()
  • Change: Fix incorrect function docblock description and remove repeated word in some parameter docblocks
  • Change: Note compatibility through WP 5.7+
  • Change: Update copyright date (2021)

1.2.11 (2020-09-09)

  • Change: Restructure unit test file structure
    • New: Create new subdirectory phpunit/ to house all files related to unit testing
    • Change: Move bin/ to phpunit/bin/
    • Change: Move tests/bootstrap.php to phpunit/
    • Change: Move tests/ to phpunit/tests/
    • Change: Rename phpunit.xml to phpunit.xml.dist per best practices
  • Change: Note compatibility through WP 5.5+

Copyright & Disclaimer

Copyright © 2009-2023 by Scott Reilly (aka coffee2code)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Discussion / Support

Have any questions, comments, or suggestions? Please provide them via the plugin’s WordPress.org support forum. I’ll do my best to reply in a timely fashion and help as best I can.

Unfortunately, I cannot provide guaranteed support, nor do I provide support via any other means.

Was this plugin useful useful to you? Consider giving it a rating. If you’re inclined to give it a poor rating, please first post to the support forum to give me a chance to address or explain the situation.

One reply on “Safe Function Call”

Leave a Reply

Your email address will not be published.