Search code examples
phpwordpresscallbacknamingmagic-methods

PHP: __call not working properly


I'm having a problem creating a class called API_Widgets in WordPress using the magic __call function. If I simple rename the file to derp.php and the class to API_Derp then it works without problems.

The following example has been stripped of everything unimportant to this issue (so if there is any error other than the specific fatal error specified in the third code block, ignore it).

Please keep in mind that I know the core.php or API class' __call works, as renaming the widgets.php or invoking another class works just fine.

core.php:

class API {

    function __call( $method, $args ) {

        $rmethod = "API_{$method}";
        if ( !class_exists( $rmethod ) ) {

            $lmethod = strtolower( $method );
            require_once( "{$lmethod}.php" );

        }

        return new $rmethod( $args );

    }

}

widgets.php:

class API_Widgets {

    private $widgets = array();

    function Add( $widgets ) {

        if ( is_array( $widgets ) ) {

            foreach ( $widgets as $widget ) {

                if ( !in_array( $widget, $this->widgets ) )
                    $this->widgets[] = $widget;

            }

        } else
            $this->widgets[] = $widgets;

    }

}

api.php:

$api = new API();
$widgets = $api->Widgets(); // Fatal error: Class 'API_Widgets' not found in /home4/goldencr/public_html/wp-content/plugins/minecraft-api/api/core.php on line 25
//$widgets->Add( 'some_widget' );

Solution

  • Extending from comment:

    Though not hinted at your question, it seems you may not actually included the widgets.php. Try to use absolute path to fix that:

    require_once( __DIR__.DIRECTORY_SEPARATOR.$lmethod.".php" );