PHP”;致命错误:找不到类“;当试图实例化从另一个文件扩展类的类时.Wordpress,但不特定于


PHP "Fatal Error: Class not found" when trying to instantiate class that extends a class from another file. Wordpress, but not specific to

这个问题是wordpress特有的,但我认为它不是wordpress特定的问题。当我尝试创建一个类型为"sample_widget"的新对象时,遇到了一个未找到类的错误。代码如下:

    global $wpdb;
    require_once(dirname(__FILE__) . '/../../../wp-load.php'); // Instantiate all the wordpress stuff, we are three subfolders removed from the /wp folder.
    require_once(dirname(__FILE__) . '/../../../wp-includes/script-loader.php'); // Instantiate all the wordpress stuff, we are three subfolders removed from the /wp folder.
    class sample_widget extends WP_Widget {
     public $widgetName = "sample_widget";
     public function __construct() {
        parent::__construct(
          $this->widgetName, // Base ID
          __('sample_widget', 'wpb_widget_domain'), // Name
          array( 'description' => __('sample_widget', 'wpb_widget_domain'), ) // Args
        );
      } // end of constructor
      public function whoami() {
        echo "This widget is called:" . $this->widgetName;
      }
      public function widget( $args, $instance ) {
        echo "Widget stuff.";
      } // end of widget function
      public function form( $instance ) {
            echo "Form stuff.";
      }
      public function update( $new_instance, $old_instance ) {
        $instance = array();
        return $instance;
      }
    } // end of class.
    add_action( 'widgets_init', function() {
         register_widget( 'sample_widget' );
    });

    function test_widget() {
        $obj = new sample_widget();
        echo "Who am I? " . $obj->whoami();
    }

结果是:致命错误:在我的文件中找不到类"sample_widget"

我在同一个文件中创建了另一个基类,并从中派生,没有任何问题。其他类实例化工作正常。不确定我做错了什么。

还有:

    $obj = new WP_Widget(); 

工作良好。

要在wordpress内部使用外部文件,您应该在顶部添加以下内容:

<?php define('WP_USE_THEMES', false); require('../../../wp-load.php'); ?>