2015-12-18 161 views
2

这可能是一个重复的问题,但是...我读到这里的几个答案,并在约类的属性(变量)和如何申报他们php.net的信息,但我不能成功应用这些知识。更确切地说,我不能将一个变量从一个函数传递给这个类中的另一个变量。我的课是为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; 

回答

-1

您可以添加任何你需要的是一个类属性:

Class WPSE_Submit_From_Front { 
    public $post_id; 
    public function set_post_id() 
    { 
      $this->post_id = $POST['id']; 
    } 
} 
+1

_class_是大写的。 $ POST不是一个有效的PHP数组($ _POST是),如果没有设置$ POST ['id'],该怎么办? – pavlovich

+0

恭喜,你指出了一些错别字,让我编辑现在 – Kisaragi

3

好了,所以里面的类可以声明私有变量:

private $post_id; 

内。然后你constructor你可以做:

$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); 
    } 

} 
+0

我在每个班级的功能被检查与'回声“帖子的ID”。 $这个 - > post_to_edit_id;'如果'$这个 - > post_id'有帖子ID作为一种价值,一切都OK,除了'handleForm()'函数,这里的'这个 - $> post_id'没有返回值(或没有按不存在,我不知道)。如果你愿意,你可以看到下一个链接的原始代码。在那里我用两个隐藏的输入字段解决了我的问题,但我不喜欢这样。 http://wordpress.stackexchange.com/a/212165/25187 – Iurie

+0

我检查了这个类中的每一行代码,但我不明白为什么'$ this-> post_id'属性是干净的(没有任何值)在'handleForm()'函数中。 'ADD_ACTION( 'template_redirect',阵列($此, 'handleForm'));':也许是因为这个功能是通过这个执行? – Iurie