如何在Widget类中创建类

Let me first show you a demo that you can use and see the problem for yourself:

WidgetClass

class TestDemo_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            false,
            __( 'TestDemo' ),
            [ 'description' => __( 'A module to display an event', 'demo' ) ] );
    }

    public function form( $instance ) {
    ?>
      <p>
        <!--get_field_id generates and ID for us to use in the update method-->
        <label for="<?= $this->get_field_id( 'test' ); ?>">login text</label>
        <input class="widefat" id="<?= $this->get_field_id( 'test' ); ?>"
               name="<?= $this->get_field_name( 'test' ); ?>" type="text"
               value="<?= esc_attr( $instance['test'] ) ?>" data-default-color="#FFF"/>
      </p>
    <?php
    }

    public function update( $new_instance, $old_instance ) {
        $instance         = $old_instance;
        $instance['test'] = $new_instance['test'];

        return $instance;
    }


    public function widget( $args, $instance ) {
        $testObj = new Test();

        echo "WIDGETS LOADED " $testObj->testParameter;
        // expected result = "WIDGETS LOADED test successful"
    }
}

Demo (Model) Class

class Test {

    private $testParameter;

    public function __construct() {
        $this->testParameter = "test successful";
    }

    public function getTestParameter() {
        return $this->testParameter;
    }

    public function setTestParameter( $testParameter) {
        $this->testParameter= $testParameter;
    }

}

The above code doesn't give me an error, but it doesn't show the widget and also removes the admin bar at the top. My question would be: How can I call a new Class inside a widget?

I tried adding a parameter inside the TestDemo_Widget and adding a object inside that parameter when update function is called. This didn't work.

I also tried adding the Object to the $instance['customname'] = new Test(); inside the update function, but this also didn't work;

The ultimate goal is to make use of models inside the widget class.

So after adding $this->loader->add_action( 'plugins_loaded', $plugin_admin, 'Test' ); and adding the dependency like require_once plugin_dir_path( dirname( __FILE__ ) ) . 'widgets/models/Test.php'; I made it work. I believe a better explanation for fixing this problem can be found here: https://wordpress.stackexchange.com/a/70060.

you can use the widget by referencing it by name:

[widget widget_name="Your_Custom_Widget"]