|
Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index
PHP Script Tips - Creating Your Own Functions
By: FYICenter.com
Part:
1
2
3
4
5
(Continued from previous part...)
What Is the Scope of a Variable Defined in a Function?
The scope of a local variable defined in a function is limited with that function.
Once the function is ended, its local variables are also removed.
So you can not access any local variable outside its defining function.
Here is a PHP script on the scope of local variables in a function:
<?php
?>
function myPassword() {
$password = "U8FIE8W0";
print("Defined inside the function? ". isset($password)."\n");
}
myPassword();
print("Defined outside the function? ". isset($password)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function?
What Is the Scope of a Variable Defined outside a Function?
A variable defined outside any functions in main script body is called global variable.
However, a global variable is not really accessible globally any in the script.
The scope of global variable is limited to all statements outside any functions.
So you can not access any global variables inside a function.
Here is a PHP script on the scope of global variables:
<?php
?>
$login = "fyicenter";
function myLogin() {
print("Defined inside the function? ". isset($login)."\n");
}
myLogin();
print("Defined outside the function? ". isset($login)."\n");
?>
This script will print:
Defined inside the function?
Defined outside the function? 1
How To Access a Global Variable inside a Function?
By default, global variables are not accessible inside a function.
However, you can make them accessible by declare them as "global" inside a function.
Here is a PHP script on declaring "global" variables:
<?php
?>
$intRate = 5.5;
function myAccount() {
global $intRate;
print("Defined inside the function? ". isset($intRate)."\n");
}
myAccount();
print("Defined outside the function? ". isset($intRate)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function? 1
How Values Are Returned from Functions?
If a value is returned from a function, it is returned by value, not by reference.
That means that a copy of the value is return.
Here is a PHP script on how values are returned from a function:
<?php
$favor = "vbulletin";
function getFavor() {
global $favor;
return $favor;
}
$myFavor = getFavor();
print("Favorite tool: $myFavor\n");
$favor = "phpbb";
print("Favorite tool: $myFavor\n");
?>
This script will print:
Favorite tool: vbulletin
Favorite tool: vbulletin
As you can see, changing the value in $favor does not affect $myFavor. This proves that
the function returns a new copy of $favor.
(Continued on next part...)
Part:
1
2
3
4
5
|