【问题标题】:PHP OOP, why does one method call require the self keyword and another doesn't?PHP OOP,为什么一个方法调用需要 self 关键字而另一个不需要?
【发布时间】:2014-06-10 04:44:23
【问题描述】:

我想更好地了解 PHP 中的 OOP。我在 C# 中使用过 OOP,但出于某种原因,它似乎比在 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()传递参数?

【问题讨论】:

  • get_style_data() 也是一个函数(不是类方法)吗?你应该得到一个错误,除非是这种情况
  • 啊!大概就是这样。我在另一个文件中具有相同的功能,该文件继承了该文件,并且该文件还没有类包装器。呃 :) 谢谢。

标签: php wordpress oop


【解决方案1】:

您对为什么这似乎有效感到困惑是对的。

据我所知,您可能正在将该类用作静态类,或者您可能正在复制其他应该更了解的编码人员的技术。简而言之,self 指的是类而不是该类的实例,但是 self,我刚刚了解到,“还提供了一种绕过当前对象的 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 但如果您使用的是实例,那么 $this 可能就是您一直在寻找的。​​p>

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

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

$template_data = array();

希望对我有所帮助。

【讨论】:

  • 感谢您的帮助。目前我没有实例化这些类,尽管这可能会改变。我还需要进一步了解 PHP 中的 OOP。
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 2014-10-07
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多