I remember back in the days when I was new to PHP, was so strange to why I can’t do echo before header.
Then I started googling
about this topic.
Basically, when you send body content to the browser before sending your header content with the header()/setcookie()/setrawcookie() methods, you wiil get an error message “Cannot modify header information – headers already sent”.
This is because the HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.
The output buffering solves this issue. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
By default the output buffering is disabled in php.ini file. There are two ways of enabling output buffering,
1. Enable output_buffering in php.ini
e.g. output_buffering = on
2. Call ob_start() method to turn on output buffering.
Let’s take an example, how it works :
Example :
1. Example with error
<?php
echo "Test";
setcookie('name', 'value');
?>
The above script will throw an error “Cannot modify header information – headers already sent”, only if the output_buffering is disabled in php.ini file.
2. Example without error
<?php
ob_start();// Turn on output buffering
echo "Test";
setcookie('name', 'value');
ob_end_flush(); // Flush (send) the output buffer and turn off output buffering
?>
The above script will work with zero error plus zero warning.
Reference : http://in2.php.net/manual/en/function.header.php
PHP5 has made a lot of improvements over php4 as regarding OOPS is concerned and performance as well.
PHP5 provides various magic methods like __construct(), __destruct(), __set(), __get(), __call(), __toString(), __sleep(), __wakeup(), __isset(), __unset(), __autoload(), __clone(). Don’t create functions with thsese names in your class unless you want the magic functionality associated with them.
These magic methods are widely used by many PHP open source frameworks like CakePHP, Garden, etc.
Lets take an example of how __call() works :
The magic method __call() gets automatically called when a call to undeclared or undefined method of a class is made.
class MyClass{
public function __call($name, $args) {
echo "Function Name : "; print_r($name);
echo "<br />";
echo "Arguments : "; print_r($args);
}
}
$myClass = new MyClass();
$myClass->setName('Mayank'); // This will call __call() method.
Output :
Function Name : setName Arguments : Array ([0] => Mayank )
Hello Everyone,
Finally, I’ve started blogging.
