Historically, the development of PHP has been somewhat haphazard. To counter this, the PHP Framework Interop Group (FIG) has created The PHP Standards Recommendation (PSR) documents that have helped bring more standardization to the language since 2009.1 The modern coding standards are contained in PSR-1 (Basic Coding Standard)2 and PSR-2 (Coding Style Guide).3
Some keywords represent things that look like functions, some look like constants, but they are actually language constructs. It is forbidden to use any keywords as constants, class names, functions or methods. Using them as variable names is allowed, but it can be confusing.4
PHP generally follows C syntax, with exceptions and enhancements for its main use in web development, which makes heavy use of string manipulation. PHP variables must be prefixed by "$". This allows PHP to perform string interpolation in double quoted strings, where backslash is supported as an escape character. No escaping or interpolation is done on strings delimited by single quotes. PHP also supports a C-like sprintf function. Code can be modularized into functions defined with keyword function. PHP supports an optional object oriented coding style, with classes denoted by the class keyword. Functions defined inside classes are sometimes called methods. Control structures include: if, while, do/while, for, foreach, and switch. Statements are terminated by a semicolon, not line endings.5
The PHP processor only parses code within its delimiters. Anything outside its delimiters is sent directly to the output and not parsed by PHP. The only open/close delimiters allowed by PSR-16 are "<?php" and "?>" or <?= and ?>.
The purpose of the delimiting tags is to separate PHP code from non-PHP data (mainly HTML). Although rare in practice, PHP will execute code embedded in any file passed to its interpreter, including binary files such as PDF or JPEG files, or in server log files.78 Everything outside the delimiters is ignored by the PHP parser and is passed through as output.9
These recommended delimiters create correctly formed XHTML and other XML documents.10 This may be helpful if the source code documents ever need to be processed in other ways during the life of the software.
If proper XML validation is not an issue, and a file contains only PHP code, it is preferable to omit the PHP closing (?>) tag at the end of the file.11
Other delimiters can be used on some servers, though most are no longer supported.12 Examples are:
Variables are prefixed with a dollar symbol and a type does not need to be specified in advance. Unlike function and class names, variable names are case-sensitive. Both double-quoted ("") and heredoc strings allow the ability to embed a variable's value into the string.13 As in C, variables may be cast to a specific type by prefixing the type in parentheses. PHP treats newlines as whitespace, in the manner of a free-form language. The concatenation operator is . (dot). Array elements are accessed and set with square brackets in both associative arrays and indexed arrays. Curly brackets can be used to access array elements, but not to assign.
PHP has three types of comment syntax: /* */ which serves as block comments, and // as well as # which are used for inline comments.14 Many examples use the print function instead of the echo function. Both functions are nearly identical; the major difference being that print is slower than echo because the former will return a status indicating if it was successful or not in addition to text to output, whereas the latter does not return a status and only returns the text for output.15
Main article: "Hello, World!" program
The usual "Hello World" code example for PHP is:16
The example above outputs the following:
Instead of using <?php and the echo statement, an optional "shortcut" is the use of <?= instead of <?php which implicitly echoes data. For example:
The above example also illustrates that text not contained within enclosing PHP tags will be directly output.
Main articles: Operator (computer programming) and Expression (computer science)
PHP supports: arithmetic operators, assignment operators, bitwise operators, comparison operators, error control operators, execution operators, increment/decrement operators, logical operators, string operators, array operators, conditional assignment operators.17
Main articles: Control flow and Statement (computer science)
Main article: Conditional (computer programming)
The syntax of a PHP if ... else statement is as follows:
For single statements, the brackets may be omitted and the if optionally condensed to a single line:
Main article: Ternary conditional operator § PHP
Main article: Elvis operator
Since PHP 5.3 supports Elvis operator (?:) in which it is possible to omit the middle part of the ternary operator.
Main article: Null coalescing operator § PHP
Since version 7.0 PHP also supports Null coalescing operator (??).
Since version 7.4 PHP also supports Null coalescing operator with the ??= syntax.
Main article: Safe navigation operator § PHP
Since version 8.0 PHP also supports Safe navigation operator (?->).
Main article: Switch statement § PHP
An example of the syntax of a PHP switch statement is as follows:
Note that unlike in C, values in case statement can be any type, not just integers.18
PHP 8 introduces the match expression.19 The match expression is conceptually similar to a switch statement and is more compact for some use cases.20 switch statements are traditionally favored for simple value-based comparisons, match statements provide more flexibility and readability, particularly when using in complex conditions or patterns 21
Main article: Control flow § Loops
Main articles: Control flow § Count-controlled loops, and For loop § 1995: PHP
The PHP syntax of a for loop is as follows:
Main articles: Control flow § Condition-controlled loops, and While loop § PHP
The syntax for a PHP while loop is as follows:
Main articles: Control flow § Condition-controlled loops, and Do while loop § PHP
The syntax for a PHP do while loop is as follows:
Main articles: Control flow § Collection-controlled loops, and Foreach loop § PHP
The syntax for a PHP for each loop is as follows:
PHP offers an alternative syntax using colons rather than the standard curly-brace syntax (of "{...}"). This syntax affects the following control structures: if, while, for, foreach, and switch. The syntax varies only slightly from the curly-brace syntax. In each case the opening brace ({) is replaced with a colon (:) and the close brace is replaced with endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.22 Mixing syntax styles within the same control block is not supported. An example of the syntax for an if/elseif statement is as follows:
This style is sometimes called template syntax, as it is often found easier to read when combining PHP and HTML or JavaScript for conditional output:
Main articles: Exception handling and Exception handling syntax § PHP
Runtime exception handling method in PHP is inherited from C++.23
Main article: Primitive data type
PHP supports four scalar types: bool, int, float, string.24
Main article: Boolean data type
PHP has a native Boolean type, named "bool", 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. Both constants true and false are case-insensitive.25
Main article: Integer (computer science)
PHP stores whole numbers in a platform-dependent range. This range is typically that of 32-bit or 64-bit signed integers.26 Integer variables can be assigned using decimal (positive and negative), octal, hexadecimal, and binary notations.
Main article: Floating-point arithmetic
Real numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.27
Main articles: String (computer science), Escape sequences in C, String interpolation § PHP, and Here document § PHP
PHP supports strings, which can be used with single quotes, double quotes, nowdoc or heredoc syntax.28
Double quoted strings support variable interpolation:
Curly braces syntax:29
Main article: Null pointer
PHP supports two special types: null, resource. The null data type represents a variable that has no value. The only value in the null data type is NULL. The NULL constant is not case sensitive.30 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.31
Main article: Compound data type
PHP supports four compound types: array, object, callable, iterable.
Main articles: Associative array, Hash table, and Comparison of programming languages (associative array) § PHP
Arrays can contain mixed elements of any type, including resources, objects.32 Multi-dimensional arrays are created by assigning arrays as array elements. PHP has no true array type. PHP arrays are natively sparse and associative. Indexed arrays are simply hashes using integers as keys.
Indexed array:
Associative array:
Multidimensional array:
Main article: Object (computer science)
The object data type is a combination of variables, functions and data structures in the object-oriented programming paradigm.
Main articles: Callable object § In PHP, and Function object § In PHP
Since version 5.3 PHP has first-class functions that can be used e.g. as an argument to another function.
Main articles: Iterator § PHP, Iterator pattern § PHP, and Generator (computer programming) § PHP
Iterable type indicate that variable can be used with foreach loop.33 It can be any array or generator or object that implementing the special internal Traversable34 interface.
Main article: Union type § PHP
Union types were introduced in PHP 8.035
Main articles: Function (computer programming), First-class function, and Higher-order function § PHP
PHP has hundreds of base functions and thousands more from extensions. Prior to PHP version 5.3.0, functions are not first-class functions and can only be referenced by their name, whereas PHP 5.3.0 introduces closures.36 User-defined functions can be created at any time and without being prototyped.37 Functions can be defined inside code blocks, permitting a run-time decision as to whether or not a function should be defined. There is no concept of local functions. Function calls must use parentheses with the exception of zero argument class constructor functions called with the PHP new operator, where parentheses are optional.
An example function definition is the following:
Function calls may be made via variables, where the value of a variable contains the name of the function to call. This is illustrated in the following example:
A default value for parameters can be assigned in the function definition, but prior to PHP 8.0 did not support named parameters or parameter skipping.38 Some core PHP developers have publicly expressed disappointment with this decision.39 Others have suggested workarounds for this limitation.40
Main article: Named arguments
Named arguments were introduced in PHP 8.0
Specifying the types of function parameters and function return values has been supported since PHP 7.0.41
Return type declaration:
Parameters typing:
Without strict typing enabled:
With strict typing enabled:
Main article: Anonymous functions § PHP
PHP supports true anonymous functions as of version 5.3.42 In previous versions, PHP only supported quasi-anonymous functions through the create_function() function.
Since version 7.4 PHP also supports arrow functions syntax (=>).43
Main article: Closure (computer programming)
Сreating closures
using
This section is an excerpt from Variadic function § In PHP.[edit]
PHP does not care about types of variadic arguments unless the argument is typed.
And typed variadic arguments:
Main articles: Generator (computer programming) § PHP, and Lazy evaluation
Using generators, we can write code that uses foreach to iterate over a dataset without having to create an array in memory, which can result in memory overhead or significant processing time for generation.
Main article: Object-oriented programming
Basic object-oriented programming functionality was added in PHP 3.44 Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance.45 In previous versions of PHP, objects were handled like primitive types.46 The drawback of this method was that the whole object was copied when a variable was assigned or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value. PHP 5 introduced private and protected member variables and methods, along with abstract classes and final classes as well as abstract methods and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore PHP 5 added Interfaces and allows for multiple Interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or IteratorAggregate can be used with the foreach language construct. The static method and class variable features in Zend Engine 2 do not work the way some would expect. There is no virtual table feature in the engine, so static variables are bound with a name instead of a reference at compile time.47
This example shows how to define a class, Foo, that inherits from class Bar. The method myStaticMethod is a public static method that can be called with Foo::myStaticMethod();.
If the developer creates a copy of an object using the reserved word clone, the Zend engine will check if a __clone() method has been defined or not. If not, it will call a default __clone() which will copy the object's properties. If a __clone() method is defined, then it will be responsible for setting the necessary properties in the created object. For convenience, the engine will supply a function that imports the properties of the source object, so that the programmer can start with a by-value replica of the source object and only override properties that need to be changed.48
This section is an excerpt from Trait (computer programming) § PHP.[edit]
This example uses a trait to enhance other classes:
This allows simulating aspects of multiple inheritance:
PSR-Huh? http://code.tutsplus.com/tutorials/psr-huh--net-29314 ↩
PSR-1 http://www.php-fig.org/psr/psr-1/ ↩
PSR-2 http://www.php-fig.org/psr/psr-2/ ↩
PHP: List of Keywords - Manual https://www.php.net/manual/en/reserved.keywords.php ↩
"Instruction separation". The PHP Group. Retrieved 2008-03-16. http://www.php.net/basic-syntax.instruction-separation ↩
"PSR-1: Basic Coding Standard - PHP-FIG". http://www.php-fig.org/psr/psr-1/ ↩
"Code injection – a simple PHP virus carried in a JPEG image". http://php.webtutor.pl/en/2011/05/13/php-code-injection-a-simple-virus-written-in-php-and-carried-in-a-jpeg-image/ ↩
Young, Susan; Aitel, Dave (24 November 2003). The Hacker's Handbook: The Strategy Behind Breaking into and Defending Networks. ISBN 9780203490044. 9780203490044 ↩
"Your first PHP-enabled page". The PHP Group. Retrieved 2008-02-25. http://ca3.php.net/manual/en/tutorial.firstpage.php ↩
Bray, Tim; et al. (26 November 2008). "Processing Instructions". Extensible Markup Language (XML) 1.0 (Fifth Edition). W3C. Retrieved 2009-06-18. http://www.w3.org/TR/2008/REC-xml-20081126/#sec-pi ↩
"PHP tags". http://php.net/manual/en/language.basic-syntax.phptags.php ↩
"PHP: Basic syntax". The PHP Group. Retrieved 2008-02-22. http://www.php.net/manual/en/language.basic-syntax.php ↩
"Variables". The PHP Group. Retrieved 2008-03-16. http://www.php.net/manual/en/language.variables.php ↩
"Comments". The PHP Group. Retrieved 2008-03-16. http://ca3.php.net/manual/en/language.basic-syntax.comments.php ↩
"print". The PHP Group. Retrieved 2008-03-16. http://www.php.net/print ↩
"Hello World". Code Newbie. Retrieved 2008-02-25. http://php.codenewbie.com/articles/php/1485/Hello_World-Page_1.html ↩
"PHP: Operators - Manual". The PHP Group. Retrieved 2021-01-30. https://www.php.net/manual/en/language.operators.php ↩
"PHP: Switch - Manual". http://php.net/manual/en/control-structures.switch.php ↩
Redmond, Paul. "Match Expression is Coming to PHP 8". Laravel News. Retrieved 4 October 2020. https://laravel-news.com/match-expression-php-8 ↩
"PHP 8.0: Match Expressions". PHP Watch. Retrieved 4 October 2020. https://php.watch/versions/8.0/match-expression ↩
"Match or Switch in PHP". Techsouce. Retrieved 27 July 2024. https://techsouce.com/match-or-switch-php-usage/ ↩
"Alternative syntax for control structures". The PHP Group. Retrieved 2010-04-16. http://php.net/manual/en/control-structures.alternative-syntax.php ↩
"PHP: Exceptions - Manual". The PHP Group. Retrieved 2021-01-30. https://www.php.net/manual/en/language.exceptions.php ↩
"Types". The PHP Group. Retrieved 2008-03-16. https://www.php.net/manual/en/language.types.php ↩
"Booleans". The PHP Group. Retrieved 2021-01-22. https://www.php.net/manual/en/language.types.boolean.php ↩
PHP: Integers - Manual https://www.php.net/manual/en/language.types.integer.php ↩
"Floating point numbers". The PHP Group. Retrieved 2021-01-22. https://www.php.net/manual/en/language.types.float.php ↩
"Strings". The PHP Group. Retrieved 2008-03-21. https://www.php.net/manual/en/language.types.string.php ↩
"Complex (curly) syntax". The PHP Group. Retrieved 2021-01-30. https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex ↩
NULL https://www.php.net/manual/en/language.types.null.php ↩
"Arrays". The PHP Group. Retrieved 2021-01-22. https://www.php.net/manual/en/language.types.array.php ↩
PHP: Iterables - Manual https://www.php.net/manual/ro/language.types.iterable.php ↩
PHP: Traversable - Manual https://www.php.net/manual/ru/class.traversable.php ↩
PHP RFC: Union Types 2.0 https://wiki.php.net/rfc/union_types_v2 ↩
"Functions". The PHP Group. Retrieved 2008-03-16. http://www.php.net/manual/en/language.functions.php ↩
"PHP 6 Dropped Items". The PHP Group. Retrieved 2009-01-09. http://wiki.php.net/todo/backlog#dropped_items ↩
"Syntax I Miss in PHP". Stanislav Malyshev, Zend Technologies, Ltd. Retrieved 2009-01-09. http://php100.wordpress.com/2009/08/21/syntax-i-miss-in-php/ ↩
"PHP Skipped and Named Parameters". SEO Egghead Inc. Retrieved 2009-01-09. http://www.seoegghead.com/software/php-parameter-skipping-and-named-parameters.seo ↩
"PHP: Type declarations - Manual". The PHP Group. Retrieved 2021-02-28. https://www.php.net/manual/en/language.types.declarations.php ↩
PHP RFC: Arrow Functions 2.0 https://wiki.php.net/rfc/arrow_functions_v2 ↩
"History of PHP and related projects". The PHP Group. Retrieved 2008-02-25. http://www.php.net/history ↩
"PHP 5 Object References". mjtsai. Retrieved 2008-03-16. http://mjtsai.com/blog/2004/07/15/php-5-object-references/ ↩
"Classes and Objects (PHP 5)". The PHP Group. Retrieved 2008-03-16. http://ca3.php.net/zend-engine-2.php ↩
"Object cloning". The PHP Group. Retrieved 2008-03-16. http://ca3.php.net/language.oop5.cloning ↩