php - 在 PHP 类中的函数之间共享变量

标签 php class properties

这可能是一个重复的问题,但是......我在这里阅读了几个答案以及 php.net 上有关类属性(变量)以及如何声明它们的信息,但我未能成功应用这些知识。更确切地说,我无法将变量从函数传递到此类中的另一个函数。我的类(class)是为 Wordpress 构建的,示意性如下所示。所有函数的运行顺序与它们在类中的顺序相同。在 getForm() 函数中,接收带有帖子 ID 的变量 $_POST['postid'] 并获取具有该 ID 的帖子。我需要的是将帖子 ID 传递给 handleForm() 函数,但我失败了。每次我尝试某些操作时,我都会收到一条消息,表明我的变量未声明。如何在这个类中正确地做到这一点?

class WPSE_Submit_From_Front {

    function __construct() {
        ...
        add_action( 'template_redirect',  array( $this, 'handleForm' ) );
    }

    function post_shortcode() {
        ...
    }

    function getForm() {

        if( 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['postid'] ) ) {
            $post_to_edit = array();
            $post_to_edit = get_post( $_POST['postid'] );
            // I want to use the $post_to_edit->ID or
            // the $_POST['postid'] in the handleForm() function
            // these two variables have the same post ID
        }

        ob_start();
        ?>

        <form method="post">
            ...
        </form>

        <?php
        return ob_get_clean();
    }

    function handleForm() {
        ...
    }

}

new WPSE_Submit_From_Front;

最佳答案

好的,在类中你可以声明私有(private)变量:

private $post_id;

然后在您的构造函数中您可以执行以下操作:

$this->post_id = $_POST['postid'];

现在,在任何类方法中,$post_id 都可以通过 $this->post_id 进行访问

在您的情况下,它看起来像这样:

class WPSE_Submit_From_Front {

    private $post_id;

    function __construct() {
        $this->post_id = $_POST['postid'];
    }

    function post_shortcode() {
        $somevar = $this->post_id;        
    }

    function getForm() {

        if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $this->post_id ) ) {
            $post_to_edit = array();
            $post_to_edit = get_post( $this->post_id );
            // ...
        }

        // ...
    }

    function handleForm() {
        do_something_new($this->post_id);
    }

}

关于php - 在 PHP 类中的函数之间共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358971/

相关文章:

c++ - 类没有合适的复制构造函数,找不到二元运算符 '=',

javascript - 如何仅在事件选项卡中获取所选选项的属性?

ant - 使用 gradle 扩展属性时如何获得 ant 行为?

c# - GameObject 属性值不会在游戏重启时重置

php ssh2_exec 不执行 'su' 命令

php - 如何扩展代码点火器 Controller 类?

php - JavaScript 菜单在 Chrome 中行为异常

PHP线程池

javascript - 使用原型(prototype)扩展另一个函数的函数

delphi - 如何向表单添加自定义属性