【问题标题】:How to change array properties within a class from member function如何从成员函数更改类中的数组属性
【发布时间】:2013-02-04 19:31:27
【问题描述】:

在下面的代码中,我试图根据“widget”函数中的 $line_above 变量的值来更改 $widget_ops “classname”数组。我不确定如何寻址数组以更改值。

这可能吗?

class my_widget extends WP_Widget {

    function my_widget() {
        $widget_ops = array('classname' => 'test', 'description' => __( "test") );
        $control_ops = array('width' => 450, 'height' => 100, 'id_base' => 'my_widget' );
        $this->WP_Widget('my_widget', __('Test: test'), $widget_ops, $control_ops);
    }

    function widget( $args, $instance ) {
        extract($args);
        $title = apply_filters( 'widget_title', empty($instance['title']) ? '' : $instance['title'], $instance );
        $text = apply_filters( 'widget_text', $instance['text'], $instance );
        $line_above = isset( $instance['line_above'] ) ? $instance['line_above'] : false;

        if($line_above){
            //TRYING TO ALTER THE CLASS HERE BASED ON VARIABLE
            $widget_ops['classname'] .= " border-top";
        }
    }
}

【问题讨论】:

    标签: php arrays class


    【解决方案1】:

    你可以让它全球化:

    class my_widget extends WP_Widget {
    
        private $widget_ops;
    
        function my_widget() {
            $this->widget_ops = array('classname' => 'test', 'description' => __( "test") );
            $control_ops = array('width' => 450, 'height' => 100, 'id_base' => 'my_widget' );
            $this->WP_Widget('my_widget', __('Test: test'), $this->widget_ops, $control_ops);
        }
    
        function widget( $args, $instance ) {
            extract($args);
            $title = apply_filters( 'widget_title', empty($instance['title']) ? '' : $instance['title'], $instance );
            $text = apply_filters( 'widget_text', $instance['text'], $instance );
            $line_above = isset( $instance['line_above'] ) ? $instance['line_above'] : false;
    
            if($line_above){
                //TRYING TO ALTER THE CLASS HERE BASED ON VARIABLE
                $this->widget_ops['classname'] .= " border-top";
            }
        }
    }
    

    【讨论】:

    • 您提供的代码不正确。通过添加“private $widget_ops”行,您正在向该类添加一个property,应该解决它; $this->widget_ops 并且只能从类本身中访问(因为它的 "visibility" 是私有的)
    • 糟糕,错过了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多