Section 3: Scripting Languages
Chapter 26: PHP Output
PHP allows for two methods of sending output to the screen. One is called print, the other echo. While they provide the same functionality, echo is a construct (it will be treated as a command), where print is an expression (it will be evaluated and will return a value). When we use print or echo in PHP, both can be used as constructs (called without parenthesis after them, as if they are a command) or as a function (called with parenthesis like a function call). Print will return a 1 as a result when it is used, while echo will not return anything.
Ultimately, the differences between print and echo are negligible. Debates over which to use range from consistency of verbiage, speed of processing (print technically takes four operating commands to echo’s three as it has one more step of returning the 1), and obscure examples of where one might win out over the other.
For our examination here, use what you like. In extreme examples, a high volume of echos will be faster than a high volume of print statements, but there are far more important places to consider refining code for speed than any gains you might find here.
To send output to the screen, we can start with the famous example of Hello, World!
- <?php echo “Hello, World!”; ?>
We can also wrap the string in parenthesis as we discussed above if you feel it makes things more clear:
- <?php echo (“Hello, World!”); ?>
Congratulations, you have just created your first PHP web page!
We can get a little more in depth before moving on with another example. When functions return something to us, we usually save that value and then take action on it. We can also send the output directly to the screen if we know it is formatted how we want to view it. The phpinfo() function for example gives us access to all the details about our server. If we use it without requesting a specific piece of information, it defaults to returning a full web page with all the details about our server. We can see this by using the following:
- <?php echo phpinfo(); ?>
This screen shot is just a portion of the entire response, which is usually several pages long. Keep this function in mind, as it is a convenient way of finding the settings of your server without digging into your config files.
Keywords, search terms: Troubleshooting php, common programming errors
Common Programming Mistakes: http://www.dummies.com/how-to/content/troubleshooting-a-php-script.html
Debugging with Print and Eclipse: http://www.ibm.com/developerworks/library/os-debug/