Functions: Syntax
PHP Functions and I
I have high knowledge of functions therefore this section of the “Zend PHP 5 Certification Blog” is likely to be short but informative. Writing functions is an essential ability I have found functions useful in many ways to such an extent I have a private ill-documented function library.
Define: Functions
A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!
Quick Function Tip
Although they are very useful, if you can use progressive code instead of functions then it is advisable to do so. I started using functions for no reason when first introduced but quickly improved the performance of my scripts by searching every script to ensure if a function is not used more than once place then it is removed.
Basic Function Syntax
Functions sytanx is very simple. To create a function we use the keyword function followed by the function name, parentheses and code block. Similar to variable names the name must consist letters, numbers and underscore only. The function can not begin with numbers and are not case sensitive.
PHP Function Echo “Hello World”:
function hello(){ echo "Hello World"; } hello(); //Outputs "Hello World";
As you notice the output of the function is a echo therefore the value returned can not be assigned to a variable or manipulated. The data stored in the function is output to the user.
PHP Function Return “Hello World”:
function hello(){ return "Hello World"; } $_hello = hello(); echo $_hello; //Outputs "Hello World" echo strtoupper($_hello); //Outputs "HELLO WORLD"
As you notice the output of the function is returned therefore the value can be assigned to a variable and manipulated. The use of RETURN is very useful, although you should be aware once the return value is assigned the function stops executing such as:
function hello(){ return "Hello World"; echo "Hello Moon"; } $_hello = hello(); echo $_hello; //Outputs "Hello World" ... Never outputs Hello Moon..
1 Comment »
RSS feed for comments on this post. TrackBack URL












did you try something like this
function hello_world()
{
echo ‘Hello World!’;
}
$_Hello = hello_world();
$_Hello;
as opposite to your first example, this has a value that can be assigned and manipulated.
according to the guide, all functions in PHP return a value even if you don’t explicitly cause them to.