Syntax.
The following Hello world program is written in PHP code embedded in an HTML document:
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
However, as PHP does not need to be embedded in HTML or used with a web server, the simplest version of a Hello World program can be written like this, with the closing tag omitted as preferred in files containing pure PHP code (prior to PHP 5.4.0, this short syntax for echo() only works with the short_open_tag configuration setting enabled, while for PHP 5.4.0 and later it is always available).
<?= 'Hello world';
The PHP interpreter only executes PHP code within its delimiters. Anything outside its delimiters is not processed by PHP (although non-PHP text is still subject to control structuresdescribed in PHP code). The most common delimiters are <?php
to open and ?>
to close PHP sections. <script language="php">
and </script>
delimiters are also available, as are the shortened forms <?
or <?=
(which is used to echo back a string or variable) and ?>
as well as ASP-style short forms <%
or <%=
and %>
. Short delimiters make script files less portable, since support for them can be disabled in the local PHP configuration, and they are therefore discouraged. The purpose of all these delimiters is to separate PHP code from non-PHP code, including HTML. The first form of delimiters, <?php
and ?>
, in XHTML and other XML documents, creates correctly formed XML "processing instructions". This means that the resulting mixture of PHP code and other markup in the server-side file is itself well-formed XML. Variables are prefixed with a dollar symbol, and a type does not need to be specified in advance. PHP 5 introduced type hinting that allows functions to force their parameters to be objects of a specific class, arrays, interfaces or callback functions. However, type hints can not be used with scalar types such as integer or string. Unlike function and class names, variable names are case sensitive. Both double-quoted (""
) and heredoc strings provide the ability to interpolate a variable's value into the string. PHP treats newlines as whitespace in the manner of a free-form language, and statements are terminated by a semicolon. PHP has three types of comment syntax: /* */
marks block and inline comments; //
as well as #
are used for one-line comments. The echo statement is one of several facilities PHP provides to output text, e.g., to a web browser. In terms of keywords and language syntax, PHP is similar to most high level languages that follow the C style syntax. if
conditions, for
and while
loops, and function returns are similar in syntax to languages such as C, C++, C#, Java and Perl.
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
However, as PHP does not need to be embedded in HTML or used with a web server, the simplest version of a Hello World program can be written like this, with the closing tag omitted as preferred in files containing pure PHP code (prior to PHP 5.4.0, this short syntax for echo() only works with the short_open_tag configuration setting enabled, while for PHP 5.4.0 and later it is always available).
<?= 'Hello world';
The PHP interpreter only executes PHP code within its delimiters. Anything outside its delimiters is not processed by PHP (although non-PHP text is still subject to control structuresdescribed in PHP code). The most common delimiters are <?php
to open and ?>
to close PHP sections. <script language="php">
and </script>
delimiters are also available, as are the shortened forms <?
or <?=
(which is used to echo back a string or variable) and ?>
as well as ASP-style short forms <%
or <%=
and %>
. Short delimiters make script files less portable, since support for them can be disabled in the local PHP configuration, and they are therefore discouraged. The purpose of all these delimiters is to separate PHP code from non-PHP code, including HTML. The first form of delimiters, <?php
and ?>
, in XHTML and other XML documents, creates correctly formed XML "processing instructions". This means that the resulting mixture of PHP code and other markup in the server-side file is itself well-formed XML. Variables are prefixed with a dollar symbol, and a type does not need to be specified in advance. PHP 5 introduced type hinting that allows functions to force their parameters to be objects of a specific class, arrays, interfaces or callback functions. However, type hints can not be used with scalar types such as integer or string. Unlike function and class names, variable names are case sensitive. Both double-quoted (""
) and heredoc strings provide the ability to interpolate a variable's value into the string. PHP treats newlines as whitespace in the manner of a free-form language, and statements are terminated by a semicolon. PHP has three types of comment syntax: /* */
marks block and inline comments; //
as well as #
are used for one-line comments. The echo statement is one of several facilities PHP provides to output text, e.g., to a web browser. In terms of keywords and language syntax, PHP is similar to most high level languages that follow the C style syntax. if
conditions, for
and while
loops, and function returns are similar in syntax to languages such as C, C++, C#, Java and Perl.
Data Types.
PHP stores whole numbers in a platform-dependent range, either a 64-bit or 32-bit signed integer equivalent to the C-language long type. Unsigned integers are converted to signed values in certain situations; this behavior is different from other programming languages. Integer variables can be assigned using decimal (positive and negative), octal,hexadecimal, and binary notations. Floating point numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation. PHP has a native Boolean type that is similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl and C++.The null data type represents a variable that has no value; NULL is the only allowed value for this data type. Variables of the "resource" type represent references to resources from external sources. These are typically created by functions from a particular extension, and can only be processed by functions from the same extension; examples include file, image, and database resources. Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled. PHP also supports strings, which can be used with single quotes, double quotes, nowdoc or heredoc syntax. The Standard PHP Library (SPL) attempts to solve standard problems and implements efficient data access interfaces and classes.
Functions.
PHP has hundreds of functions provided by the core language functionality and thousands more available via various extensions; these functions are well documented in the online PHP documentation. However, the built-in library has a wide variety of naming conventions and associated inconsistencies, as described under history above.
Additional functions can be defined by the developer:
function myAge($birthYear) // defines a function, this one is named "myAge" { $yearsOld = date('Y') - $birthYear; // calculates the age return $yearsOld . ' year' . ($yearsOld != 1 ? 's' : ''); // returns the age in a descriptive form } echo 'I am currently ' . myAge(1981) . ' old.'; // outputs the text concatenated // with the return value of myAge() // As the result of this syntax, myAge() is called. // In 2014, the output of this sample program will be 'I am currently 33 years old.'
In PHP, normal functions are not first-class and can only be referenced by their name directly, or dynamically by a variable containing the name of the function (referred to as "variable functions"). User-defined functions can be created at any time without being prototyped. Functions can be defined inside code blocks, permitting a run-time decisionas to whether or not a function should be defined. Function calls must use parentheses, with the exception of zero-argument class constructor functions called with the PHPnew
operator, where parentheses are optional. Until PHP 5.3, support for true anonymous functions or closures did not exist in PHP. Whilecreate_function()
exists since PHP 4.0.1, it is merely a thin wrapper aroundeval()
that allows normal PHP functions to be created during program execution. Also, support for variable functions allows normal PHP functions to be used, for example, ascallbacks or within function tables. PHP 5.3 added support for closures, which are true anonymous, first-class functions, whose syntax can be seen in the following example:
function getAdder($x) { return function($y) use ($x) { return $x + $y; }; } $adder = getAdder(8); echo $adder(2); // prints "10"In the example above,getAdder()
function creates a closure using passed argument$x
(the keyworduse
imports a variable from the lexical context), which takes an additional argument$y
, and returns the created closure to the caller. Such a function is a first-class object, meaning that it can be stored in a variable, passed as a parameter to other functions, etc.Thegoto
flow control statement is used as in the following example:function lock() { $file = fopen('file.txt', 'r+'); retry: if (!flock($file, LOCK_EX | LOCK_NB)) goto retry; fwrite($file, 'Success!'); fclose($file); }Whenflock()
is called, PHP opens a file and tries to lock it. The target labelretry:
defines the point to which execution should return ifflock()
is unsuccessful andgoto retry;
is called. Thegoto
statement is restricted and requires that the target label be in the same file and context.Thegoto
statement has been supported since PHP 5.3.