0% found this document useful (0 votes)
67 views17 pages

PHP Basic

The document discusses PHP syntax and tags. It explains that PHP code is enclosed within opening and closing tags like <?php ?> and that there are different tag styles that can be used. It also covers PHP comments, variables, variable naming conventions, default variable values, and predefined variables. The key points are: - PHP code is delimited by opening and closing tags like <?php ?> - There are different tag styles including short tags (<? ?>) that may not be supported on all servers - Variables start with $ and are case-sensitive - Variables can be assigned by reference using & - Uninitialized variables default to false, 0, empty string, or empty array
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
67 views17 pages

PHP Basic

The document discusses PHP syntax and tags. It explains that PHP code is enclosed within opening and closing tags like <?php ?> and that there are different tag styles that can be used. It also covers PHP comments, variables, variable naming conventions, default variable values, and predefined variables. The key points are: - PHP code is delimited by opening and closing tags like <?php ?> - There are different tag styles including short tags (<? ?>) that may not be supported on all servers - Variables start with $ and are case-sensitive - Variables can be assigned by reference using & - Uninitialized variables default to false, 0, empty string, or empty array
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 17

Basic syntax

Escaping from HTML:

When PHP parses a file, it looks for opening and closing tags, which tell PHP to start
and stop interpreting the code between them.

Parsing in this manner allows php to be embedded in all sorts of different documents, as
everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the
time you will see php embedded in HTML documents, as in this example.

<p>This is going to be ignored.</p>


<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored.</p>

You can also use more advanced structures:

Example 10.1. Advanced escaping

<?php
if ($expression) {
?>
<strong>This is true.</strong>
<?php
} else {
?>
<strong>This is false.</strong>
<?php
}
?>

This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting
whatever it finds (except for an immediately following newline - see instruction separation ) until it
hits another opening tag. The example given here is contrived, of course,
but for outputting large blocks of text, dropping out of PHP parsing mode is generally
more efficient than sending all of the text through echo() or print().
There are four different pairs of opening and closing tags which can be used in php.
Two of those, <?php ?> and <script language="php"> </script>, are always available.
The other two are short tags and ASP style tags, and can be turned on and off from the
php.ini configuration file.

As such, while some people find short tags and ASP style tags convenient, they are less portable, and
generally not recommended.

Note: Also note that if you are embedding PHP within XML or XHTML you will need
to use the <?php ?> tags to remain compliant with standards.

Example 10.2. PHP Opening and Closing Tags


1. <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>

2. <script language="php">
echo 'some editors (like FrontPage) don\'t
like processing instructions';
</script>

3. <? echo 'this is the simplest, an SGML processing instruction'; ?>


<?= expression ?> This is a shortcut for "<? echo expression ?>"

4. <% echo 'You may optionally use ASP-style tags'; %>


<%= $variable; # This is a shortcut for "<% echo . . ." %>

While the tags seen in examples one and two are both always available, example one is the most
commonly used, and recommended, of the two.

Short tags (example three) are only available when they are enabled via the short_open_tag php.ini
configuration file directive, or if php was configured with the --enable-short-tags option.

ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini
configuration file directive.

Note: Using short tags should be avoided when developing applications or libraries that are meant
for redistribution, or deployment on PHP servers which are not under your control, because short
tags may not be supported on the target server.

For portable, redistributable code, be sure not to use short tags.

short_open_tag

Tells whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to
use PHP in combination with XML, you can disable this option in order to use <?xml ?>
inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml
version="1.0"'; ?>. Also if disabled, you must use the long form of the PHP open tag (<?
php ?>).

Note: This directive also affects the shorthand <?=, which is identical to <? echo.
Use of this shortcut requires short_open_tag to be on.

asp_tags

Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes
the variable-value printing shorthand of <%= $value %>.

Instruction separation
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each
statement.

The closing tag of a block of PHP code automatically implies a semicolon; you do not
need to have a semicolon terminating the last line of a PHP block.

The closing tag for the block will include the immediately trailing newline if one is present.

<?php
echo 'This is a test';
?>

<?php echo 'This is a test' ?>

<?php echo 'We omitted the last closing tag';


Note: The closing tag of a PHP block at the end of a file is optional,

and in some cases omitting it is helpful when using include() or require(), so unwanted
whitespace will not occur at the end of files, and you will still be able to add headers to the
response later. It is also handy if you use output buffering, and would not like to see added
unwanted whitespace at the end of the parts generated by the included files.

Comments:

PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:

<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>

The "one-line" comment styles only comment to the end of the line or the current block of PHP
code, whichever comes first. This means that

HTML code after // ... ?> or # ... ?> WILL be printed. ?> breaks out of PHP mode and
returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration
directive is enabled, it behaves the same with // %> and # %>.
However, the </script> tag doesn't break out of PHP mode in a one-line comment.

<h1>This is an <?php # echo 'simple';?> example.</h1>


<p>The header above will say 'This is an example'.</p>

'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style
comments. It is easy to make this mistake if you are trying to comment out a large block
of code.
<?php
/*
echo 'This is a test'; /* This comment will cause a problem */
*/
?>

Variables
Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable.

The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).

Note: $this is a special variable that can't be assigned.

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number


$_4site = 'not yet'; // valid; starts with an underscore
$tyte = 'mansikka'; // valid; '' is (Extended) ASCII 228.
?>

As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means
that the new variable simply references (in other words, "becomes an alias for" or "points to") the
original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is
being assigned (the source variable). For instance, the following code snippet outputs 'My name is
Bob' twice:

<?php
$foo = 'Bob'; // Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.
?>
One important thing to note is that only named variables may be assigned by reference.

<?php
$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.

function test()
{
return 25;
}

$bar = &test(); // Invalid.


?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized
variables have a default value of their type - FALSE, zero, empty string or an empty array.

Example 12.1. Default values of uninitialized variables

<?php
echo ($unset_bool ? "true" : "false"); // false
$unset_int += 25; // 0 + 25 => 25
echo $unset_string . "abc"; // "" . "abc" => "abc"
$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
?>

Relying on the default value of an uninitialized variable is problematic in the case of including one
file into another which uses the same variable name. It is also a major security risk with
register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized
variables, however not in the case of appending elements to the uninitialized array.

isset() language construct can be used to detect if a variable has been already initialized.

Predefined variables

PHP provides a large number of predefined variables to any script which it runs. Many of these
variables, however, cannot be fully documented as they are dependent upon which server is running,
the version and setup of the server, and other factors. Some of these variables will not be available
when PHP is run on the command line. For a listing of these variables, please see the section on
Reserved Predefined Variables.

Warning
In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major
change in PHP. Having register_globals off affects the set of predefined variables available in the
global scope. For example, to get DOCUMENT_ROOT you'll use
$_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL
http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.

For related information on this change, read the configuration entry for register_globals, the security
chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements.

Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.

From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables
from the web server (if applicable), the environment, and user input. These new arrays are rather
special in that they are automatically global--i.e., automatically available in every scope. For this
reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined
superglobals.) The superglobals are listed below; however, for a listing of their contents and further
discussion on PHP predefined variables and their natures, please see the section Reserved Predefined
Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of
PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays
directive.

Variable variables: Superglobals cannot be used as variable variables inside functions or class
methods.

Note: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not
identical, so modifying one will not change the other.

If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also
left empty.

PHP Superglobals

$GLOBALS
Contains a reference to every variable which is currently available within the global scope of
the script. The keys of this array are the names of the global variables. $GLOBALS has
existed since PHP 3.
$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of
the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still
available, but deprecated).
$_GET
Variables provided to the script via URL query string. Analogous to the old
$HTTP_GET_VARS array (which is still available, but deprecated).
$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS
array (which is still available, but deprecated).
$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old
$HTTP_COOKIE_VARS array (which is still available, but deprecated).
$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old
$HTTP_POST_FILES array (which is still available, but deprecated). See POST method
uploads for more information.
$_ENV
Variables provided to the script via the environment. Analogous to the old
$HTTP_ENV_VARS array (which is still available, but deprecated).
$_REQUEST

Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and
which therefore cannot be trusted. The presence and order of variable inclusion in this array
is defined according to the PHP variables_order configuration directive. This array has no
direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().

Caution

Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST.

Note: When running on the command line , this will not include the argv and argc
entries; these are present in the $_SERVER array.

$_SESSION
Variables which are currently registered to a script's session. Analogous to the old
$HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session
handling functions section for more information.

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:

<?php
$a = 1; /* global scope */

function Test()
{
echo $a; /* reference to local scope variable */
}

Test();
?>

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 within this scope. You may notice that this is a little bit
different from the C language in that global variables in C are automatically available to functions
unless specifically overridden by a local definition. This can cause some problems in that people
may inadvertently change a global variable. In PHP global variables must be declared global inside a
function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example 12.2. Using global

<?php
$a = 1;
$b = 2;

function Sum()
{
global $a, $b;

$b = $a + $b;
}

Sum();
echo $b;
?>

The above 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 be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined
$GLOBALS array. The previous example can be rewritten as:

Example 12.3. Using $GLOBALS instead of global


<?php
$a = 1;
$b = 2;

function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

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 because $GLOBALS is a superglobal. Here's an example demonstrating the power
of superglobals:

Using static variables

Another important feature of variable scoping is the static variable.

A static variable exists only in a local function scope, but it does not lose its value
when program execution leaves this scope.

Consider the following example:

Example 12.5. Example demonstrating need for static variables

<?php
function Test()
{
$a = 0;
echo $a;
$a++;
}
?>

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 variable
disappears. To make a useful counting function which will not lose track of the current count, the $a
variable is declared static:

Example 12.6. Example use of static variables

<?php
function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>

Now, every time the Test() function is called it will print the value of $a and increment it.

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:

Example 12.7. Static variables with recursive functions

<?php
function Test()
{
static $count = 0;

$count++;
echo $count;
if ($count < 10) {
Test();
}
$count--;
}
?>

Note: Static variables may be declared as seen in the examples above.

Trying to assign values to these variables which are the result of expressions will cause a
parse error.

Example 12.8. Declaring static variables

<?php
function foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)

$int++;
echo $int;
}
?>
Variable variables

Sometimes it is convenient to be able to have variable variable names.

That is, a variable name which can be set and used dynamically.

A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the
above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents
"hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if
you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you
wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this
ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or
class methods. The variable $this is also a special variable that cannot be referenced dynamically.

Variables from outside PHP

HTML Forms (GET and POST)


When a form is submitted to a PHP script, the information from that form is automatically made
available to the script. There are many ways to access this information, for example:

Example 12.9. A simple HTML form

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


Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>

Depending on your particular setup and personal preferences, there are many ways to access data
from your HTML forms. Some examples are:

Example 12.10. Accessing data from a simple POST HTML form

<?php
// Available since PHP 4.1.0

echo $_POST['username'];
echo $_REQUEST['username'];

import_request_variables('p', 'p_');
echo $p_username;

// Available since PHP 3. As of PHP 5.0.0, these long predefined


// variables can be disabled with the register_long_arrays directive.

echo $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on. As of


// PHP 4.2.0 the default value of register_globals = off.
// Using/relying on this method is not preferred.

echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET
also applies to the QUERY_STRING (the information after the '?' in a URL). So, for
example, http://www.example.com/test.php?id=3 contains GET data which is accessible with
$_GET['id']. See also $_REQUEST and import_request_variables().

Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was
always on. The PHP community is encouraging all to not rely on this directive as it's preferred to
assume it's off and code accordingly.

Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned
on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB
insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.

PHP also understands arrays in the context of form variables (see the related faq). You may, for
example, group related variables together, or use this feature to retrieve values from a multiple select
input. For example, let's post a form to itself and upon submission display the data:

Example 12.11. More complex form variables

<?php
if ($_POST) {
echo '<pre>';
echo htmlspecialchars(print_r($_POST, true));
echo '</pre>';
}
?>
<form action="" method="post">
Name: <input type="text" name="personal[name]" /><br />
Email: <input type="text" name="personal[email]" /><br />
Beer: <br />
<select multiple name="beer[]">
<option value="warthog">Warthog</option>
<option value="guinness">Guinness</option>
<option value="stuttgarter">Stuttgarter Schwabenbru</option>
</select><br />
<input type="submit" value="submit me!" />
</form>

In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such
restriction applies.

IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a
tag like:

<input type="image" src="image.gif" name="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the
server with two additional variables, sub_x and sub_y. These contain the coordinates of the user
click within the image. The experienced may note that the actual variable names sent by the browser
contains a period rather than an underscore, but PHP converts the period to an underscore
automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a
mechanism for storing data in the remote browser and thus tracking or identifying return users. You
can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the
SetCookie function must be called before any output is sent to the browser. This is the same
restriction as for the header() function. Cookie data is then available in the appropriate cookie data
arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie()
manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For
example:

<?php
setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two separate cookies although MyCookie will now be a single array in your script. If
you want to set just one cookie with multiple values, consider using serialize() or explode() on the
value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path
or domain is different. So, for a shopping cart application you may want to keep a counter and pass
this along. i.e.

Example 12.12. A setcookie() example

<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it
should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For
the reason, look at it: <?php
$varname.ext; /* invalid variable name */
?> Now, what the parser sees is a variable named $varname, followed by the string concatenation
operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or
reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in
incoming variable names with underscores.

Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not
always obvious what type a given variable is at any one time. PHP includes several functions which
find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and
is_string(). See also the chapter on Types.

Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change
during the execution of the script (except for magic constants, which aren't actually constants).

A constant is case-sensitive by default. By convention, constant identifiers are


always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with
a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Example 13.1. Valid and invalid constant names

<?php

// Valid constant names


define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");

// Invalid constant names


define("2FOO", "something");

// This is valid, but should be avoided:


// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).

Like superglobals, the scope of a constant is global.

You can access constants anywhere in your script without regard to scope. For more information
on scope, read the manual section on variable scope.

Syntax

You can define a constant by using the define()-function. Once a constant is defined, it
can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in constants. Do
not define resource constants.

You can get the value of a constant by simply specifying its name. Unlike with variables, you should
not prepend a constant with a $. You can also use the function constant() to read a constant's value if
you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all
defined constants.

Note: Constants and (global) variables are in a different namespace. This implies that for
example TRUE and $TRUE are generally different.

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as
if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be
issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first
define() bar as a constant). If you simply want to check if a constant is set, use the defined()
function.

These are the differences between constants and variables:

Constants do not have a dollar sign ($) before them;


Constants may only be defined using the define() function, not by simple
assignment;
Constants may be defined and accessed anywhere without regard to
variable scoping rules;
Constants may not be redefined or undefined once they have been set; and
Constants may only evaluate to scalar values.

Example 13.2. Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these
constants, however, are created by various extensions, and will only be present when those
extensions are available, either via dynamic loading or because they have been compiled in.

There are five magical constants that change depending on where they are used. For example, the
value of __LINE__ depends on the line that it's used on in your script. These special constants are
case-insensitive and are as follows:

Table 13.1. A few "magical" PHP constants

Name Description
__LINE__ The current line number of the file.
The full path and filename of the file. If used inside an include, the name of the
__FILE__ included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path
whereas in older versions it contained relative path under some circumstances.
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
__FUNCTION__ function name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.
__CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class
name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-
__METHOD__
sensitive).

You might also like