Php 如何在小部件类中创建类
首先让我向您展示一个演示,您可以自己使用并查看问题: WidgetClassPhp 如何在小部件类中创建类,php,wordpress,Php,Wordpress,首先让我向您展示一个演示,您可以自己使用并查看问题: WidgetClass class TestDemo_Widget extends WP_Widget { public function __construct() { parent::__construct( false, __( 'TestDemo' ), [ 'description' => __( 'A module to dis
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"
}
}
class Test {
private $testParameter;
public function __construct() {
$this->testParameter = "test successful";
}
public function getTestParameter() {
return $this->testParameter;
}
public function setTestParameter( $testParameter) {
$this->testParameter= $testParameter;
}
}
上面的代码没有给我一个错误,但它没有显示小部件,也删除了顶部的管理栏。我的问题是:如何在小部件中调用新类?
我尝试在TestDemo\u小部件中添加一个参数,并在调用update
函数时在该参数中添加一个对象。这不管用
我还尝试将对象添加到$instance['customname']=newtest()中
在更新
功能中,但这也不起作用
最终目标是利用widget类内部的模型。您可以通过名称引用widget来使用它:
[widget widget_name=“Your_Custom_widget”]因此在添加$this->loader->add_操作('plugins_loaded',$plugin_admin,'Test')
并添加依赖项,如require_once plugin_dir_path(dirname(_FILE__))。'widgets/models/Test.php'代码>我成功了。我相信可以在这里找到解决此问题的更好解释:。但是如何在小部件类中调用类/对象?