PHP syntax and semantics

Uses your system voice; voice and rate in settings.

Snapshot

≈ 12 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted. 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-1 are " " 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. Everything outside the delimiters is ignored by the PHP parser and is passed through as output. These recommended delimiters create correctly formed XHTML and other XML documents. 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. " " and " " (removed in PHP7) Short opening tags ( ) (configured with the short_open_tag ini setting) A special form of the tag is , which automatically echos the next statement. Prior to PHP 5.4.0 this was also controlled with short_open_tag , but is always available in later versions. ASP style tags ( or ) (removed in PHP7) The example above outputs the following: Hello World! Instead of using and the echo statement, an optional "shortcut" is the use of instead of which implicitly echoes data. For example: PHP "Hello, World!" program The above example also illustrates that text not contained within enclosing PHP tags will be directly output. ==Operators== PHP supports arithmetic operators, assignment operators, bitwise operators, comparison operators, error control operators, execution operators, increment/decrement operators, logical operators, string operators, array operators, and conditional assignment operators. ===Arithmetic and string operators=== Addition, subtraction, multiplication, and division are expressed using + , - , * , and / operators (respectively), modulus with % , exponentiation with ** , and increment and decrement with ++ and -- (respectively). Concatenation is expressed with . , and appending text to an existing string is represented as .= . ===Comparison operators=== == compares two values and outputs true if their values are equal. != or <> compares if their values are not equal. === and !== compare if both their value and the data types are equal. and > represent less than and greater than, respectively. and >= represent less than or equal and greater than or equal, respectively. The spaceship operator ( ), introduced in PHP 7, compares the values to the left and the right of the operator. If they are equal, it outputs 0 , if the value on the left is greater, 1 , and if the value on the right is greater, -1 . ===Logical operators=== && or and represents logical conjunction, and || or or represents logical disjunction. ! represents logical negation, and cannot be substituted with not . ===Conditional operators=== PHP: Ternary operators PHP: Ternary operators $c = $a ?: $b; /* Equivalent to */ $c = $a ? $a : $b; $a = $b ?? $c; /* Equivalent to */ $a = isset($b) ? $b : $c; Since version 7.4, PHP also supports the null coalescing operator with the ??= syntax. $a ??= $b; /* Equivalent to */ $a = $a ?? $b; $variable = $object?->method(); /* Equivalent to */ $variable = $object !== null ? $object->method() : null; if (condition) { // statements; } elseif (condition2) { // statements; } else { // statements; } For single statements, the brackets may be omitted and the if optionally condensed to a single line: if (condition) dosomething(); elseif (condition2) dosomethingelse(); else doyetathirdthing(); switch (expr) { case 0: // statements; break; case 1: // statements; break; case 2: // statements; break; default: // statements; } Note that unlike in C, values in case statement can be any type, not just integers. echo match (1) { 0 => 'Foo', 1 => 'Bar', 2 => 'Baz', }; //> Bar for (initialization; condition; update) { // statements; } while (condition) { // statements; } do { // statements; } while (condition); foreach ($set as $value) { // statements; } if (condition): // code here elseif (condition): // code here else: // code here endif; 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: Tomorrow is Friday! TGIF ugh function inv($x) { if ($x == 0) { throw new Exception('Division by zero'); } return 1 / $x; } try { echo inv(2); // prints 0.5 echo inv(0); // throw an exception echo inv(5); // will not run } catch (Exception $e) { echo $e->getMessage(); // prints Division by zero } // Continue execution echo "Hello"; // prints Hello $a = 1234; // decimal number $b = 0321; // octal number (equivalent to 209 decimal) $c = 0x1B; // hexadecimal number (equivalent to 27 decimal) $d = 0b11; // binary number (equivalent to 3 decimal) $e = 1_234_567; // decimal number (as of PHP 7.4.0) $a = 1.234; $b = 1.2e3; // 1200 $c = 7E-5; // 0.00007 $d = 1_234.567; // as of PHP 7.4.0 $age = '23'; echo "John is $age years old"; // John is 23 years old Curly braces syntax: $f = "sqrt"; $x = 25; echo "a$xc\n"; // Warning: Undefined variable $xc echo "a{$x}c\n"; // prints a25c echo "a${x}c\n"; // also prints a25c echo "$f($x) is {$f($x)}\n"; // prints sqrt(25) is 5 $season = ["Autumn", "Winter", "Spring", "Summer"]; echo $season[2]; // Spring Associative array: $salary = ["Alex" => 34000, "Bill" => 43000, "Jim" => 28000]; echo $salary["Bill"]; // 43000 Multidimensional array: $mark = [ "Alex" => [ "biology" => 73, "history" => 85 ], "Jim" => [ "biology" => 86, "history" => 92 ] ]; echo $mark["Jim"]["history"]; // 92 class Person { //... } $person = new Person(); function runner(callable $function, mixed ...$args) { return $function(...$args); } $f = fn($x, $y) => $x ** $y; function sum(int|float ...$args) { return array_sum($args); } echo runner(fn($x) => $x ** 2, 2); // prints 4 echo runner($f, 2, 3); // prints 8 echo runner('sum', 1, 2, 3, 4); // prints 10 function printSquares(iterable $data) { foreach ($data as $value) { echo ($value ** 2) . " "; } echo "\n"; } // array $array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // generator $generator = function (): Generator { for ($i = 1; $i function foo(string|int $foo): string|int {} ==Type juggling== PHP attempts to convert values to the expected data type when it encounters an unexpected data type. This is known as type juggling. PHP throws a TypeError if the value cannot be interpreted. ===Numeric contexts=== PHP treats any string that contains the value of an integer as an integer in arithmetic operations, and does the same for floats. When a string starts with an integer or float followed by other characters (e.g. '5star' ), PHP ignores the later characters and treats the value as 5 . When a string does not start with an integer or float, it is treated as 0. ===String contexts=== In string operations, PHP treats values as strings. It also treats true as '1' , and false as . ===Logical contexts=== In logical operations, PHP treats values as booleans. Specifically, PHP treats 0 , 0.0 , '0' , , array&#91;&#93; , and null as false , and any other value is treated as true . ===Comparative contexts=== In comparative operations, PHP treats null as "" when the second argument is a string. When the first argument is a boolean or null , it converts both arguments to a boolean. Objects and arrays are always treated as greater than non-objects or arrays, respectively. ==Functions== 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. User-defined functions can be created at any time and without being prototyped. 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 hello($target='World') { echo "Hello $target!\n"; } hello(); // outputs "Hello World!" hello('Wikipedia'); // outputs "Hello Wikipedia!" 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: function hello() { return 'Hello'; } function world() { return "World!"; } $function1 = 'hello'; $function2 = 'world'; echo "{$function1()} {$function2()}"; 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. Some core PHP developers have publicly expressed disappointment with this decision. Others have suggested workarounds for this limitation. function power($base, $exp) { return $base ** $exp; } // Using positional arguments: echo power(2, 3); // prints 8 // Using named arguments: echo power(base: 2, exp: 3); // prints 8 echo power(exp: 3, base: 2); // prints 8 function sum($a, $b): float { return $a + $b; } var_dump(sum(1, 2)); // prints float(3) Parameters typing: function sum(int $a, int $b) { return $a + $b; } var_dump(sum(1, 2)); // prints int(3) var_dump(sum(1.6, 2.3)); // prints int(3) Strict typing is enabled with declare(strict_types = 1); . In strict typing, type juggling is disabled and a TypeError is raised when types mismatch or if a function returns the wrong data type. For example: Without strict typing enabled: $f1 = fn ($a, $b): int => $a + $b; $f2 = fn (int $a, int $b) => $a + $b; var_dump($f1(1.3, 2.6)); // prints int(3) var_dump($f1(1, '2')); // prints int(3) var_dump($f2(1.3, 2.6)); // prints int(3) var_dump($f2(1, '2')); // prints int(3) With strict typing enabled: declare(strict_types=1); $f1 = fn ($a, $b): int => $a + $b; $f2 = fn (int $a, int $b) => $a + $b; var_dump($f1(1.3, 2.6)); // Fatal error: Return value must be of type int, float returned var_dump($f1(1, '2')); // prints int(3) var_dump($f2(1.3, 2.6)); // Fatal error: Argument #1 ($a) must be of type int, float given var_dump($f2(1, '2')); // Fatal error: Argument #2 ($b) must be of type int, string given $x = 3; $func = function($z) { return $z * 2; }; echo $func($x); // prints 6 Since version 7.4 PHP also supports arrow functions syntax ( => ). $x = 3; $func = fn($z) => $z * 2; echo $func($x); // prints 6 $add = fn($x) => fn($y) => $y + $x; /* Equivalent to */ $add = function ($x) { return function ($y) use ($x) { return $y + $x; }; }; using $f = $add(5); echo $f(3); // prints 8 echo $add(2)(4); // prints 6 ==Generators== 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. ==Objects== Basic object-oriented programming functionality was added in PHP 3. Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance. In previous versions of PHP, objects were handled like primitive types. 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. 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(); . class Foo extends Bar { function __construct() { $doo = "wah dee dee"; } public static function myStaticMethod() { $dee = "dee dee dum"; } } 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.

Text derived from https://en.wikipedia.org/w/index.php?oldid=1368167940 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

Extracted from the cited revision's reference blocks; absent citations are not invented.