PHP OOP,为什么一个方法调用需要self关键字而另一个方法不需要?

时间:2014-06-10 04:44:24

标签: php wordpress oop

我想更好地理解PHP中的OOP。我在C#中使用OOP,但由于某种原因,它在PHP中看起来比在PHP中更直观。

让我困惑的一件事是,在我写的这个特定方法中,我在同一个类中调用了另外两个方法。对于其中一个调用我必须使用self关键字而另一个我不使用。我很好奇是否有人能告诉我这里的不同之处?

以下是相关代码:

class scbsUpdateTemplate {

    // After all the form values have been validated, it's all sent here to be
    // formatted and put into the database using update_option()
    function update_template() {

        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
        }

        $post_data = $_POST;

        if ( !wp_verify_nonce( $post_data['_wpnonce'],
                    'ecbs-edit-templates' ) ) {
            wp_die( __( 'You do not have permission to update this page.' ) );
        }


        $style_data = get_style_data();

        $template_data = self::find_style_elements( $post_data, $style_data );

        // Some other stuff down here
    }

    function get_style_data() {

        return scbsStyleClass::get_style_data();
    }

    function find_style_elements( $post_data, $style_data ) {
        // find the values from the post data that are needed to create
        // the template and put them into a template values array
        foreach ( $post_data as $style => $value ) {
            if ( array_key_exists( $style,
                        $style_data ) )
                $template_data[$style] = $value;
        }

        return $template_data;
    }
}

如果我在调用find_style_elements()时不使用self关键字,则会收到未定义的函数错误,但get_style_data()不需要关键字。是因为我将参数传递给find_style_elements()

1 个答案:

答案 0 :(得分:0)

你应该对这为何会起作用感到困惑。

据我所知,你可能正在使用该类作为静态,或者你可能正在复制其他应该更了解的编码器的技术。简而言之,自我指的是类,而不是那个类的实例,但是我刚刚学会了自我“还提供了一种绕过当前对象的vtable的方法。”大多数时候我希望有人需要使用$ this,但有一点不同:When to use self over $this?

确实你可能需要更多地使用$ this。例如,这一行:

    $style_data = get_style_data();

因为这是调用一个名为get_style_data()的全局函数,如果你没有得到错误,我必须存在。要调用对象的方法,它必须是

    $style_data = $this->get_style_data();

虽然

    $style_data = self::get_style_data();

对我来说会有类似的结果。如果你静态地调用这个类,那么你肯定想要使用self,但是如果你正在使用一个实例,那么$这可能就是你一直在寻找的。

如果您打算将此类视为单例,那么我可以理解为什么您可以使用self,即使所有内部方法调用都必须使用。

在其他新闻中我可以建议您在使用之前在$ template_data方法中初始化变量$ template_data吗?

$template_data = array();

我希望我得到了一些帮助。