Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
PHP
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Syntax == {{Main|PHP syntax and semantics}} [[File:"Hello World" Application in PHP.png|thumb|A "Hello, World" application in PHP 7.4 running on its built-in development server]] The following [["Hello, World!" program]] is written in PHP code embedded in an [[HTML]] document: <syntaxhighlight lang="html+php" highlight="7-9"> <!DOCTYPE html> <html> <head> <title>PHP "Hello, World!" program</title> </head> <body> <p><?= 'Hello, World!' ?></p> </body> </html> </syntaxhighlight> However, as no requirement exists for PHP code to be embedded in HTML, the simplest version of ''Hello, World!'' may be written like this, with the closing tag <syntaxhighlight lang="PHP" inline="">?></syntaxhighlight> omitted as preferred in files containing pure PHP code.<ref>{{cite web|url=https://www.php.net/manual/en/language.basic-syntax.phptags.php |title=tags{{snd}} Manual |website=php.net |access-date=2014-02-17}}</ref> <syntaxhighlight lang="php5"> <?php echo 'Hello, World!'; </syntaxhighlight> The PHP interpreter only executes PHP code within its [[delimiter]]s. Anything outside of its delimiters is not processed by PHP, although the non-PHP text is still subject to [[control structure]]s described in PHP code. The most common delimiters are <syntaxhighlight lang="PHP" inline=""><?php</syntaxhighlight> to open and <syntaxhighlight lang="PHP" inline="">?></syntaxhighlight> to close PHP sections. The shortened form <syntaxhighlight lang="PHP" inline=""><?</syntaxhighlight> also exists. This short delimiter makes script files less portable since support for them can be disabled in the local PHP configuration and it is therefore discouraged.<ref name="php.net-2008" /><ref name="The PHP Group-3">{{cite web|title=PHP: Basic syntax|url=https://www.php.net/manual/en/language.basic-syntax.php|publisher=The PHP Group|access-date=2008-02-22}}</ref> Conversely, there is no recommendation against the echo short tag <syntaxhighlight lang="PHP" inline=""><?=</syntaxhighlight>.<ref>{{cite web|access-date=2016-01-03|url=https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md|title=Basic Coding Standard|publisher=PHP Framework Interoperability Group}}</ref> Prior to PHP 5.4.0, this short syntax for <syntaxhighlight lang="php" inline="">echo</syntaxhighlight> only works with the <code>short_open_tag</code> configuration setting enabled, while for PHP 5.4.0 and later it is always available.<ref>{{cite web|url=https://www.php.net/echo |title=echo{{snd}} Manual |website=php.net |access-date=2014-02-17}}</ref><ref>{{cite web|url=https://www.php.net/manual/en/ini.core.php#ini.short-open-tag |title=Description of core php.ini directives{{snd}} Manual |website=php.net |date=2002-03-17 |access-date=2014-02-17}}</ref><ref name="php.net-2008">{{cite web |url=http://wiki.php.net/rfc/shortags |title=PHP: rfc:shortags |website=php.net |date=2008-04-03 |access-date=2014-05-08 }}</ref> The purpose of all these delimiters is to separate PHP code from non-PHP content, such as [[JavaScript]] code or HTML markup.<ref>{{cite web|access-date=2008-02-25|url=https://www.php.net/manual/en/tutorial.firstpage.php|title=Your first PHP-enabled page |publisher=The PHP Group}}</ref> So the shortest [["Hello, World!" program]] written in PHP is: <syntaxhighlight lang="html+php"> <?='Hello, World!'; </syntaxhighlight> The first form of delimiters, <syntaxhighlight lang="PHP" inline><?php</syntaxhighlight> and <syntaxhighlight lang="PHP" inline>?></syntaxhighlight>, in [[XHTML]] and other [[XML]] documents, creates correctly formed XML processing instructions.<ref>{{cite web | url = http://www.w3.org/TR/2008/REC-xml-20081126/#sec-pi | title = Processing Instructions | work = Extensible Markup Language (XML) 1.0 (Fifth Edition) | publisher = W3C | date = 26 November 2008 | last = Bray | first = Tim | access-date = 2009-06-18|display-authors=etal}}</ref> This means that the resulting mixture of PHP code and other markups in the server-side file is itself well-formed XML. {{Anchor|TYPE-HINTING}} Variables are [[sigil (computer programming)|prefixed]] with a [[dollar sign|dollar symbol]], and a [[primitive type|type]] does not need to be specified in advance. PHP 5 introduced ''type declarations'' that allow functions to force their parameters to be objects of a specific class, arrays, interfaces or [[callback function]]s. However, before PHP 7, type declarations could not be used with scalar types such as integers or strings.<ref name="php.net-2015b" /> Below is an example of how PHP variables are declared and initialized. <syntaxhighlight lang="php"> <?php $name = 'John'; // variable of string type being declared and initialized $age = 18; // variable of integer type being declared and initialized $height = 5.3; // variable of double type being declared and initialized echo $name . ' is ' . $height . "m tall\n"; // concatenating variables and strings echo "$name is $age years old."; // interpolating variables to string ?> </syntaxhighlight> 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.<ref>{{cite web|access-date=2008-03-16|url=https://www.php.net/manual/en/language.variables.php|title=Variables |publisher=The PHP Group}}</ref> PHP treats [[newline]]s as [[whitespace character|whitespace]] in the manner of a [[free-form language]], and statements are terminated by a semicolon.<ref>{{cite web|access-date=2008-03-16|url=https://www.php.net/basic-syntax.instruction-separation|title=Instruction separation |publisher=The PHP Group}}</ref> PHP has three types of [[comparison of programming languages (syntax)#Comments|comment syntax]]: <syntaxhighlight lang="PHP" inline>/* */</syntaxhighlight> marks block and inline comments; <syntaxhighlight lang="PHP" inline>//</syntaxhighlight> or <syntaxhighlight lang="PHP" inline>#</syntaxhighlight> are used for one-line comments.<ref>{{cite web|access-date=2008-03-16|url=https://www.php.net/manual/en/language.basic-syntax.comments.php|title=Comments |publisher=The PHP Group}}</ref> The <code>echo</code> statement is one of several facilities PHP provides to output text.{{Citation needed|date=November 2023}} In terms of keywords and language syntax, PHP is similar to C-style syntax. <syntaxhighlight lang="PHP" inline>if</syntaxhighlight> conditions, <syntaxhighlight lang="PHP" inline>for</syntaxhighlight> and <syntaxhighlight lang="PHP" inline>while</syntaxhighlight> loops and function returns are similar in syntax to languages such as C, C++, C#, Java and Perl.{{Citation needed|date=November 2023}} === Data types === PHP is [[strong and weak typing|loosely typed]]. It stores integers in a platform-dependent range, either as a 32, 64 or 128-bit [[signed number representations|signed]] [[integer (computer science)|integer]] equivalent to the [[C variable types and declarations|C-language long type]]. Unsigned integers are converted to signed values in certain situations, which is different behaviour to many other programming languages.<ref>{{cite web | url = http://www.mysqlperformanceblog.com/2007/03/27/integers-in-php-running-with-scissors-and-portability/ | title = Integers in PHP, running with scissors, and portability | date = March 27, 2007 | publisher = MySQL Performance Blog | access-date = 2007-03-28}}</ref> Integer variables can be assigned using decimal (positive and negative), [[octal]], [[hexadecimal]], and [[binary number|binary]] notations.<ref>{{cite web|access-date=2025-05-26|url=https://www.php.net/manual/en/language.types.integer.php|title=Integers|website=PHP Manual |publisher=The PHP Group}}</ref> [[Floating-point number]]s are also stored in a platform-specific range. They can be specified using floating-point notation, or two forms of [[scientific notation]].<ref name="The PHP Group-2">{{cite web|access-date=2008-03-16|url=https://www.php.net/manual/en/language.types.php|title=Types |publisher=The PHP Group}}</ref> PHP has a native [[Boolean data type|Boolean]] type that is similar to the native Boolean types in [[Java (programming language)|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++.<ref name="The PHP Group-2" /> The null data type represents a variable that has no value; <code>NULL</code> is the only allowed value for this data type.<ref name="The PHP Group-2" /> 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.<ref name="The PHP Group-2" /> 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 [[hash table|hashes]] with both keys and values, and the two can be intermingled.<ref name="The PHP Group-2" /> PHP also supports [[string (computing)|strings]], which can be used with single quotes, double quotes, nowdoc or [[heredoc]] syntax.<ref>{{cite web|access-date=2008-03-21|url=https://www.php.net/manual/en/language.types.string.php|title=Strings |publisher=The PHP Group}}</ref> The '''Standard PHP Library''' (SPL) attempts to solve standard problems and implements efficient data access interfaces and classes.<ref>{{cite web | url = https://www.php.net/spl | title = SPL β StandardPHPLibrary | date = March 16, 2009 | website = PHP.net | access-date = 2009-03-16}}</ref> === Functions === PHP defines a large array of functions in the core language and many are also available in various extensions; these functions are well documented online [https://www.php.net/docs.php PHP documentation].<ref name="php.net-2014a" /> However, the built-in library has a wide variety of naming conventions and associated inconsistencies, as described under [[#History|history]] above. Custom functions may be defined by the developer: <syntaxhighlight lang="php"> function myAge(int $birthYear): string { // calculate the age by subtracting the birth year from the current year. $yearsOld = date('Y') - $birthYear; // return the age in a descriptive string. return $yearsOld . ($yearsOld == 1 ? ' year' : ' years'); } echo 'I am currently ' . myAge(1995) . ' old.'; </syntaxhighlight> As of {{CURRENTYEAR}}, the output of the above sample program is "I am currently {{#expr: {{CURRENTYEAR}} - 1995}} years old." In lieu of [[function pointer]]s, functions in PHP can be referenced by a string containing their name. In this manner, normal PHP functions can be used, for example, as [[Callback function|callbacks]] or within [[function table]]s.<ref name="php.net-2014c" /> User-defined functions may be created at any time without being [[Function prototype|prototyped]].<ref name="php.net-2014a">{{cite web | url = https://www.php.net/manual/en/functions.user-defined.php | title = User-defined functions (PHP manual) | date = 2014-07-04 | access-date = 2014-07-07 | website = php.net }}</ref><ref name="php.net-2014c">{{cite web | url = https://www.php.net/manual/en/functions.variable-functions.php | title = Variable functions (PHP manual) | date = 2014-07-04 | access-date = 2014-07-07 | website = php.net }}</ref> Functions may be defined inside code blocks, permitting a [[dynamic dispatch|run-time decision]] as to whether or not a function should be defined. There is a <code>function_exists</code> function that determines whether a function with a given name has already been defined. Function calls must use parentheses, with the exception of zero-argument class [[constructor (computer science)|constructor]] functions called with the PHP operator <code>new</code>, in which case parentheses are optional.{{Citation needed|date=November 2023}} Since PHP 4.0.1 <code>create_function()</code>, a thin wrapper around <code>eval()</code>, allowed normal PHP functions to be created during program execution; it was deprecated in PHP 7.2 and removed in PHP 8.0<ref>{{cite web | url = https://www.php.net/manual/en/function.create-function.php | title = create_function() (PHP manual) | date = 2022-04-06 | access-date = 2022-05-04 | website = php.net }}</ref> in favor of syntax for [[anonymous function]]s or "[[Closure (computer programming)|closures]]"<ref>{{cite web | url = https://www.php.net/manual/en/functions.anonymous.php | title = Anonymous functions (PHP manual) | date = 2014-07-04 | access-date = 2014-07-07 | website = php.net }}</ref> that can capture variables from the surrounding scope, which was added in PHP 5.3. Shorthand arrow syntax was added in PHP 7.4:<ref>{{cite web | url = https://www.php.net/manual/en/functions.arrow.php | title = Arrow Functions (PHP manual) | access-date = 2021-01-25 | website = php.net }}</ref> <syntaxhighlight lang="php"> function getAdder($x) { return fn($y) => $x + $y; } $adder = getAdder(8); echo $adder(2); // prints "10" </syntaxhighlight> In the example above, <code>getAdder()</code> function creates a closure using passed argument {{code|lang=php|code=$x}}, which takes an additional argument {{code|lang=php|code=$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 (computer programming)|parameter]] to other functions, etc.<ref>{{cite web | url = http://wiki.php.net/rfc/closures | title = Request for Comments: Lambda functions and closures | date = 2008-07-01 | access-date = 2014-07-07 | author1 = Christian Seiler | author2 = Dmitry Stogov | website = php.net }}</ref> Unusually for a dynamically typed language, PHP supports type declarations on function parameters, which are enforced at runtime. This has been supported for classes and interfaces since PHP 5.0, for arrays since PHP 5.1, for "callables" since PHP 5.4, and scalar (integer, float, string and boolean) types since PHP 7.0.<ref name="php.net-2015b" /> PHP 7.0 also has type declarations for function return types, expressed by placing the type name after the list of parameters, preceded by a colon.<ref name="php.net-2015a" /> For example, the <code>getAdder</code> function from the earlier example could be annotated with types like so in PHP 7: <syntaxhighlight lang="php"> function getAdder(int $x): Closure { return fn(int $y): int => $x + $y; } $adder = getAdder(8); echo $adder(2); // prints "10" echo $adder(null); // throws an exception because an incorrect type was passed $adder = getAdder([]); // would also throw an exception </syntaxhighlight> By default, scalar type declarations follow weak typing principles. So, for example, if a parameter's type is <code>int</code>, PHP would allow not only integers, but also convertible numeric strings, floats or Booleans to be passed to that function, and would convert them.<ref name="php.net-2015b" /> However, PHP 7 has a "strict typing" mode which, when used, disallows such conversions for function calls and returns within a file.<ref name="php.net-2015b" /> === PHP objects === Basic [[object-oriented programming]] functionality was added in PHP 3 and improved in PHP 4.<ref name="The PHP Group" /> This allowed for PHP to gain further abstraction, making creative tasks easier for programmers using the language. Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance.<ref name="mjtsai.com" /> In previous versions of PHP, objects were handled like [[value type]]s.<ref name="mjtsai.com">{{cite web|access-date=2008-03-16|url=http://mjtsai.com/blog/2004/07/15/php-5-object-references/|title=PHP 5 Object References |website=mjtsai.com}}</ref> The drawback of this method was that code had to make heavy use of PHP's "reference" variables if it wanted to modify an object it was passed rather than creating a copy of it. In the new approach, objects are referenced by [[handle (computing)|handle]], and not by value.{{Citation needed|date=November 2023}} PHP 5 introduced private and protected [[member variable]]s and methods, along with [[abstract type|abstract classes]], [[final type|final classes]], [[abstract method]]s, and [[final method]]s. It also introduced a standard way of declaring [[Constructor (computer science)|constructors]] and [[Destructor (computer science)|destructors]], similar to that of other object-oriented languages such as [[C++]], and a standard [[exception handling]] model. Furthermore, PHP 5 added [[Interface (computing)|interfaces]] and allowed for multiple interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. [[object (computer science)|Objects]] implementing ArrayAccess can be used with [[array data type|array]] syntax and objects implementing [[Iterator]] or [[IteratorAggregate]] can be used with the <code>foreach</code> [[language construct]]. There is no [[virtual table]] feature in the engine, so [[static variable]]s are bound with a name instead of a reference at compile time.<ref name="The PHP Group-4">{{cite web|access-date=2008-03-16|url=http://www.php.net/zend-engine-2.php|title=Classes and Objects (PHP 5) |publisher=The PHP Group}}</ref> If the developer creates a copy of an object using the reserved word <code>clone</code>, the Zend engine will check whether a <code>__clone()</code> method has been defined. If not, it will call a default <code>__clone()</code> which will copy the object's properties. If a <code>__clone()</code> 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 the programmer can start with a by-value [[wikt:replica|replica]] of the source object and only override properties that need to be changed.<ref>{{cite web|access-date=2008-03-16|url=https://www.php.net/language.oop5.cloning|title=Object cloning |publisher=The PHP Group}}</ref> The [[Visibility (computer science)|visibility]] of PHP properties and methods is defined using the [[Keyword (computer programming)|keywords]] <code>public</code>, <code>private</code>, and <code>protected</code>. The default is public, if only [[variable (programming)|var]] is used; <code>var</code> is a synonym for <code>public</code>. Items declared <code>public</code> can be accessed everywhere. <code>protected</code> limits access to [[inherited class]]es (and to the class that defines the item). <code>private</code> limits visibility only to the class that defines the item.<ref>{{cite web |url=http://theserverpages.com/php/manual/en/language.oop5.visibility.php |title=Visibility (PHP Manual) |website=theserverpages.com |date=2005-05-19 |access-date=2010-08-26 |archive-date=2010-09-24 |archive-url=https://web.archive.org/web/20100924033414/http://theserverpages.com/php/manual/en/language.oop5.visibility.php |url-status=dead }}</ref> Objects of the same type have access to each other's private and protected members even though they are not the same instance.{{Citation needed|date=November 2023}} ==== Example ==== The following is a basic example of [[object-oriented programming]] in PHP 8: <syntaxhighlight lang="php" line> <?php abstract class User { protected string $name; public function __construct(string $name) { // make first letter uppercase and the rest lowercase $this->name = ucfirst(strtolower($name)); } public function greet(): string { return "Hello, my name is " . $this->name; } abstract public function job(): string; } class Student extends User { public function __construct(string $name, private string $course) { parent::__construct($name); } public function job(): string { return "I learn " . $this->course; } } class Teacher extends User { public function __construct(string $name, private array $teachingCourses) { parent::__construct($name); } public function job(): string { return "I teach " . implode(", ", $this->teachingCourses); } } $students = [ new Student("Alice", "Computer Science"), new Student("Bob", "Computer Science"), new Student("Charlie", "Business Studies"), ]; $teachers = [ new Teacher("Dan", ["Computer Science", "Information Security"]), new Teacher("Erin", ["Computer Science", "3D Graphics Programming"]), new Teacher("Frankie", ["Online Marketing", "Business Studies", "E-commerce"]), ]; foreach ([$students, $teachers] as $users) { echo $users[0]::class . "s:\n"; array_walk($users, function (User $user) { echo "{$user->greet()}, {$user->job()}\n"; }); } </syntaxhighlight> This program outputs the following: {{samp|Students:<br> Hello, my name is Alice, I learn Computer Science<br> Hello, my name is Bob, I learn Computer Science<br> Hello, my name is Charlie, I learn Business Studies<br> Teachers:<br> Hello, my name is Dan, I teach Computer Science, Information Security<br> Hello, my name is Erin, I teach Computer Science, 3D Graphics Programming<br> Hello, my name is Frankie, I teach Online Marketing, Business Studies, E-commerce|style=padding-left:0px; overflow-x: hidden; word-wrap: break-word;}} <!-- Note that there are problems with the script in this section. -->
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)