Reputation: 2248
This can be a duplicate question, but ... I read several answers here and the info on php.net about class properties (variables) and how to declare them, but I fail to apply successfully this knowledge. More exactly, I can't pass a variable from a function to another within this class. My class was built for Wordpress and schematically looks as below. All functions runs in the same order as they are in the class. In the getForm()
function a variable $_POST['postid']
with a post ID is received and the post with this ID is taken. What I need is to pass the post ID to the handleForm()
function and I fail this. Every time I try something I receive a message that my variable was not declared. How to do this correctly in this class?
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;
Upvotes: 2
Views: 1077
Reputation: 1942
Ok so inside the class you can declare private variable:
private $post_id;
Then inside your constructor
you can do:
$this->post_id = $_POST['postid'];
Now in any of your class methods $post_id will be accessible as $this->post_id
In your case it would look like this:
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);
}
}
Upvotes: 4
Reputation: 2218
You can add whatever you need as a class property:
Class WPSE_Submit_From_Front {
public $post_id;
public function set_post_id()
{
$this->post_id = $POST['id'];
}
}
Upvotes: -2