PHP Infomatics 3
PHP Infomatics 3
SYNTAX:
- A user defined function declaration starts with the word "function":
function functionName() {
code to be executed;
}
- A function name can start with a letter or underscore (not a number).
- Give the function a name that reflects what the function does.
- Function names are NOT case-sensitive.
- In the example below, we create a function named "writeMsg()". The opening
curly brace ( { ) indicates the beginning of the function code and the closing
curly brace ( } ) indicates the end of the function. The function outputs "Hello
world!". To call the function, just write its name:
RESULT: Hello World!
ARGUMENTS:
- Information can be passed to functions through arguments. An argument is
just like a variable.
- Arguments are specified after the function name, inside the parentheses.
- You can add as many arguments as you want, just separate them with a
comma.
- The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and
the name is used inside the function, which outputs several different first
names, but an equal last name:
- The following example has a function with two arguments ($fname and
$year):
RETURNING VALUES:
- To let a function return a value, use the return statement:
VARIABLE FUNCTIONS:
- PHP supports the concept of variable functions. This means that if a variable
name has parentheses appended to it, PHP will look for a function with the
same name as whatever the variable evaluates to, and will attempt to
execute it.
- Among other things, this can be used to implement callbacks, function tables,
and so forth.
- Variable functions won't work with language constructs such as echo, print,
unset(), isset(), empty(), include, require and the like.
- Utilize wrapper functions to make use of any of these constructs as variable
functions.
EXAMPLES:
VARIABLE SCOPE:
- The scope of a variable is the context within which it is defined. For the
most part all PHP variables only have a single scope. This single scope spans
included and required files as well. For example:
<?php
$a = 1;
include 'b.inc';
?>
- Here the $a variable will be available within the included b.inc script.
However, within user-defined functions a local function scope is introduced.
- Any variable used inside a function is by default limited to the local
function scope. For example:
EXAMPLE #2:
To make a useful counting function which will not
lose track of the current count, the $a variable is
declared static. Now, $a is initialized only in
first call of function and every time the test()
function is called it will print the value of $a
- Static variables also provide one way to deal with recursive functions.
- A recursive function is one which calls itself. Care must be taken when writing
a recursive function because it is possible to make it recurse indefinitely. You
must make sure you have an adequate way of terminating the recursion.
- The following simple function recursively counts to 10, using the static variable
$count to know when to stop:
FUNCTION REFERENCES:
Memtrack
OPcache
runkit
uopz
KTaglib
oggvorbis OGG/Vorbis
Authentication Services
KADM5 Kerberos V
Radius
Newt
Bzip2
LZF
Phar
Zip
Cryptography Extensions
Crack Cracklib
CSPRNG
Mcrypt
Mhash
OpenSSL
Password Hashing
Database Extensions
Abstraction Layers
Calendar
Direct IO
Directories
Filesystem
Inotify
Mimetype
Proctitle
xattr
xdiff
FriBiDi
Gettext
iconv
Multibyte String
Pspell
Cairo
Gmagick
Mailparse
vpopmail
Mathematical Extensions
Lapack
Statistics
Eio
Ev
Expect
Libevent
POSIX
pthreads
Shared Memory
Sync
Lua
Streams
Tidy
Tokenizer
URLs
Taint
Other Services
Event
FTP
Gearman
Gupnp
Hyperwave API
Memcache
Memcached
mqseries
Network
RRD RRDtool
SNMP
Sockets
SVN Subversion
Varnish
YAZ
YP/NIS
ZooKeeper
mnoGoSearch
Apache
NSAPI
Session Extensions
Text Processing
Strings
Arrays
Classkit
Data Structures
Function Handling
Quickhash
Reflection
Variable handling
Web Services
OAuth
SCA
SOAP
XML-RPC
win32ps
win32service
XML Manipulation
libxml
SimpleXML
WDDX
XML Parser
XMLReader
XMLWriter
XSL
GUI Extensions
UI
PASSING BY REFERENCE:
- You can pass a variable by reference to a function so the function can modify the
variable. The syntax is as follows:
PASSING BY VALUE:
In PHP, when a variable is assigned a value, you have three things:
Because PHP takes care of all the dirty work (and is generally an easy language to use), you dont need to concern yourself with this last thing. All you
have to do is refer to a variable (after its been assigned a value) to retrieve that value. By default, when you use that variable in a function call as in the
above, youre passing the value of the variable to the function, not the variable itself. In other words, in that above list of three things, only the middle
thingthe valueis received by the function. Take this example:
$it = 'Larry';
say_hello($it);
say_hello('Larry');
An important consideration when it comes to passing variables by value is that if the function changes the value of $thing, the $it variable outside of
the function is unaffected:
$it = 'Larry';
$thing = 'World';
say_hello($it);
say_hello($it);
Those two function calls will print the same Hello, Larry message twice.
It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the
include or require statement.
The include and require statements are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use the
include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use the
require statement to include a key file to the flow of execution. This will help avoid compromising your application's
security and integrity, just in-case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all
your web pages. Then, when the header needs to be updated, you can only update the header include file.
Syntax
include 'filename';
or
require 'filename';
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:
Example
<html>
<body>
</body>
</html>
Run example
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done (we are using a <div> element so
that the menu easily can be styled with CSS later):
Example
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
Run example
Example 3
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling file:
Example
<html>
<body>
</body>
</html>
Run example
However, there is one big difference between include and require; when a file is included with
the include statement and PHP cannot find it, the script will continue to execute:
Example
<html>
<body>
</body>
</html>
Run example
If we do the same example using the require statement, the echo statement will not be executed because the
script execution dies after the require statement returned a fatal error:
Example
<html>
<body>
</body>
</html>
Run example
Use require when the file is required by the application.
Use include when the file is not required and application should continue when file is not found.
The PHP superglobals $_GET and $_POST are used to collect form-data.
Example
<html>
<body>
</body>
</html>
Run example
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP
file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<html>
<body>
</body>
</html>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
</body>
</html>
Run example
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to validate form data to
protect your script from malicious code.
This page does not contain any form validation, it just shows how you can send and retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data
is important to protect your form from hackers and spammers!
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file without having to do
anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to
server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.