Você está na página 1de 22

PHP FUNCTIONS

- A function is a block of statements that can be used repeatedly in a


program.
- A function will not execute immediately when a page loads.
- A function will be executed by a call to the function.

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):

DEFAULT ARGUMENT VALUE:


The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as
argument:

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:

This script will not


produce any output
because the echo
statement refers to a
local version of the $a
variable, and it has not
been assigned a value
A. The global keyword
EXAMPLE #1:

The script will output 3. By declaring


$a and $b global within the
function, all references to either
variable will refer to the global
version. There is no limit to the
number of global variables that can

EXAMPLE #2: Using $GLOBALS instead of global


The $GLOBALS array is an
associative array with the name
of the global variable being the
key and the contents of that
variable being the value of the
array element. Notice how
$GLOBALS exists in any scope, this is

B. Using static variables


A static variable exists only in a local function scope, but it does not lose its
value when program execution leaves this scope.
EXAMPLE #1:
This function is quite useless
since every time it is called it sets
$a to 0 and prints 0. The $a++
which increments the variable
serves no purpose since as soon
as the function exits the $a

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:

Affecting PHP's Behaviour

APC Alternative PHP Cache


APCu APC User Cache

APD Advanced PHP debugger

bcompiler PHP bytecode Compiler

BLENC Blenc - BLowfish ENCoder for PHP source scripts

Error Handling Error Handling and Logging

htscanner htaccess-like support for all SAPIs

inclued Inclusion hierarchy viewer

Memtrack

OPcache

Output Control Output Buffering Control

PHP Options/Info PHP Options and Information

runkit

scream Break the silence operator

uopz

Weakref Weak References

WinCache Windows Cache for PHP

Xhprof Hierarchical Profiler

Audio Formats Manipulation

ID3 ID3 Tags

KTaglib

oggvorbis OGG/Vorbis

OpenAL OpenAL Audio Bindings

Authentication Services

KADM5 Kerberos V
Radius

Command Line Specific Extensions

Ncurses Ncurses Terminal Screen Control

Newt

Readline GNU Readline

Compression and Archive Extensions

Bzip2

LZF

Phar

Rar Rar Archiving

Zip

Zlib Zlib Compression

Credit Card Processing

MCVE MCVE (Monetra) Payment

SPPLUS SPPLUS Payment System

Cryptography Extensions

Crack Cracklib

CSPRNG

Hash HASH Message Digest Framework

Mcrypt

Mhash

OpenSSL

Password Hashing

Database Extensions
Abstraction Layers

Vendor Specific Database Extensions

Date and Time Related Extensions

Calendar

Date/Time Date and Time

HRTime High resolution timing

File System Related Extensions

Direct IO

Directories

Fileinfo File Information

Filesystem

Inotify

Mimetype

Proctitle

xattr

xdiff

Human Language and Character Encoding Support

Enchant Enchant spelling library

FriBiDi

Gender Determine gender of firstnames

Gettext

iconv

intl Internationalization Functions

Multibyte String
Pspell

Recode GNU Recode

Image Processing and Generation

Cairo

Exif Exchangeable image information

GD Image Processing and GD

Gmagick

ImageMagick Image Processing (ImageMagick)

Mail Related Extensions

Cyrus Cyrus IMAP administration

IMAP IMAP, POP3 and NNTP

Mail

Mailparse

vpopmail

Mathematical Extensions

BC Math BCMath Arbitrary Precision Mathematics

GMP GNU Multiple Precision

Lapack

Math Mathematical Functions

Statistics

Trader Technical Analysis for Traders

Non-Text MIME Output

FDF Forms Data Format

GnuPG GNU Privacy Guard


haru Haru PDF

Ming Ming (flash)

PDF

PS PostScript document creation

RPM Reader RPM Header Reading

Process Control Extensions

Eio

Ev

Expect

Libevent

PCNTL Process Control

POSIX

Program execution System program execution

pthreads

Semaphore Semaphore, Shared Memory and IPC

Shared Memory

Sync

Other Basic Extensions

GeoIP Geo IP Location

FANN FANN (Fast Artificial Neural Network)

JSON JavaScript Object Notation

Judy Judy Arrays

Lua

Misc. Miscellaneous Functions


Parsekit

SPL Standard PHP Library (SPL)

SPL Types SPL Type Handling

Streams

Tidy

Tokenizer

URLs

V8js V8 Javascript Engine Integration

Yaml YAML Data Serialization

Yaf Yet Another Framework

Taint

Other Services

chdb Constant hash database

cURL Client URL Library

Event

FAM File Alteration Monitor

FTP

Gearman

Gopher Net Gopher

Gupnp

Hyperwave API

LDAP Lightweight Directory Access Protocol

Memcache

Memcached
mqseries

Network

RRD RRDtool

SAM Simple Asynchronous Messaging

SNMP

Sockets

SSH2 Secure Shell2

Stomp Stomp Client

SVM Support Vector Machine

SVN Subversion

TCP TCP Wrappers

Varnish

YAZ

YP/NIS

0MQ messaging ZMQ

ZooKeeper

Search Engine Extensions

mnoGoSearch

Solr Apache Solr

Sphinx Sphinx Client

Swish Swish Indexing

Server Specific Extensions

Apache

FastCGI Process Manager


IIS IIS Administration

NSAPI

Session Extensions

Msession Mohawk Software Session Handler Functions

Sessions Session Handling

Session PgSQL PostgreSQL Session Save Handler

Text Processing

BBCode Bulletin Board Code

PCRE Regular Expressions (Perl-Compatible)

POSIX Regex Regular Expression (POSIX Extended)

ssdeep ssdeep Fuzzy Hashing

Strings

Variable and Type Related Extensions

Arrays

Classes/Objects Class/Object Information

Classkit

Ctype Character type checking

Data Structures

Filter Data Filtering

Function Handling

Quickhash

Reflection

Variable handling

Web Services
OAuth

SCA

SOAP

Yar Yet Another RPC Framework

XML-RPC

Windows Only Extensions

COM COM and .Net (Windows)

win32ps

win32service

XML Manipulation

DOM Document Object Model

libxml

SDO Service Data Objects

SDO-DAS-Relational SDO Relational Data Access Service

SDO DAS XML SDO XML Data Access Service

SimpleXML

WDDX

XMLDiff XML diff and merge

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:

The following things can be passed by


reference:

1. Variables, i.e. foo($a)


2. New statements, i.e. foo(new
foobar())
3. References returned from functions,

PASSING BY VALUE:
In PHP, when a variable is assigned a value, you have three things:

The variables name (like it in the above example)

The variables value (Larry)

Memory allotted on the computer, where that value will be stored.

(Theres a bit more going on but)

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';

function say_hello ($thing) {

echo "Hello, $thing";

say_hello($it);

That code is functionally equivalent to

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';

function say_hello ($thing) {

echo "Hello, $thing";

$thing = 'World';

say_hello($it);

say_hello($it);

Those two function calls will print the same Hello, Larry message twice.

PHP INCLUDE AND REQUIRE

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 include Examples


Example 1
Assume we have a standard footer file called "footer.php", that looks like this:

<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</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>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

</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>

<h1>Welcome to my home page!</h1>


<?php include 'vars.php';
echo "I have a $color $car.";
?>

</body>
</html>

Run example

PHP include vs. require


The require statement is also used to include a file into the PHP code.

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>

<h1>Welcome to my home page!</h1>


<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</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>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</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.

PHP FORM HANDLING:

The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a submit button:

Example
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</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>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

Welcome John
Your email address is john.doe@example.com

The same result could also be achieved using the HTTP GET method:

Example
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Run example

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</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.

Think SECURITY when processing PHP forms!

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!

GET vs. POST


Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array
holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

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.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all variable names and values are
displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000
characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can
be useful in some cases.

GET may be used for sending non-sensitive data.

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.

Developers prefer POST for sending form data.

Você também pode gostar