Kunok
Kunok

Reputation: 8759

Global variable doesn't work (within one class)

I have three methods within my class. One prints content. Other processes form and third one returns errors. Within method that processes form I have global variable where are errors stored. However when I want to use it within method that returns errors, It simply doesn't see it.

Errors method:

private function return_errors(){
        return $error_messages;
    }

Form process method:

private function process_form(){
        if (isset($_POST['submit'])) {

            # Assign data
            $username = $_POST['username'];
            $email = $_POST['email'];
            $password = $_POST['password'];
            $confirm_password = $_POST['confirm-password'];

            # Dialog array
            global $error_messages;
            $error_messages = 'test';
            ...

Print function:

public function print_content(){

            # Process form data
            $this->process_form();

            # output buffering start
            ob_start();

            # print navbar
            $this->print_navbar();

            # declare output buffering content
            $output = ob_get_contents();

            # add more output data
            $output .= ' alot of string...'.$this->print_dialog().'...more string.';
            # end output buffering and return it
            ob_end_clean();
            return $output;
}

So the thing is, if I use return 'test string' in return_errors method it prints 'test string' at the right place correctly. However when I use return $error_messages that method doesn't return anything at all.

Upvotes: 0

Views: 48

Answers (2)

pavlovich
pavlovich

Reputation: 1942

Better - add $error_messages to SESSION:

session_start();    
$_SESSION['error_messages'] = 'test';

elsewhere check if we have error messages:

if(!empty($_SESSION['error_messages'])) {
   $error_messages = $_SESSION['error_messages'];
   unset($_SESSION['error_messages']);
}

Upvotes: 1

Waqar Haider
Waqar Haider

Reputation: 971

because error message don't have anything

$error_message doesn't have something to show

Upvotes: 0

Related Questions