2
\$\begingroup\$
class Redirect {

    public function __construct() {
    }

    public function to($key, $page) {
        if(isset($page) && !empty($page)) {
            header('Location: ?' . $key . '=' . $page);
            exit();
        }
    }

}

With this class I can use this:

$foo->redirect('page', 'home'); 

instead of this:

header('Location: ?page=home);
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Well, for starters, your redirect will never work if you pass in both $key and $page, as you're asking for the following:

1. is not isset($page)
2. is not empty($page)

Which means that the redirect will happen only when $page is NOT set and NOT empty. Because empty() calls isset() internally, you should only need this:

if(!empty($page))

Additionally, you're not managing your buffers. Ideally, you should use the ob_ functions as well as headers_sent() to check if headers have already been sent. If you don't manage your buffer, you're very likely to hit the infamous "Cannot modify header information - headers already sent" error. This post goes into further detail on how to fix that error, especially using the ob_ functions.

Aside from all that, your construct is doing nothing. If your Redirect class only has the to() method, perhaps you're better off making it a standalone function, or adding additional functionality.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Thank you for your time, the isset was a mistake by me. And I did't know about the ob_ functions. I will look into it! Again many thanks! \$\endgroup\$
    – Proliner
    Oct 7, 2014 at 16:16
  • \$\begingroup\$ Certainly! They are quite powerful in buffering your output. \$\endgroup\$
    – jsanc623
    Oct 7, 2014 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.