The
syntax
In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
and
semantics
Semantics is the study of linguistic Meaning (philosophy), meaning. It examines what meaning is, how words get their meaning, and how the meaning of a complex expression depends on its parts. Part of this process involves the distinction betwee ...
of
PHP
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
, a
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
, form a set of rules that define how a PHP program can be written and interpreted.
Overview
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. The modern coding standards are contained in PSR-1 (Basic Coding Standard) and PSR-2 (Coding Style Guide).
Keywords
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.
*
__halt_compiler()
*
abstract
*
and
*
array()
*
as
*
break
*
callable
(as of PHP 5.4)
*
case
*
catch
*
class
*
clone
*
const
*
continue
*
declare
*
default
*
die()
*
do
*
echo
*
else
*
elseif
*
empty()
*
enddeclare
*
endfor
*
endforeach
*
endif
*
endswitch
*
endwhile
*
eval()
*
exit()
*
extends
*
final
*
finally
(as of PHP 5.5)
*
fn
(as of PHP 7.4)
*
for
*
foreach
*
function
*
global
*
goto
(as of PHP 5.3)
*
if
*
implements
*
include
*
include_once
*
instanceof
*
insteadof
(as of PHP 5.4)
*
interface
*
isset()
*
list()
*
match
(as of PHP 8.0)
*
namespace
(as of PHP 5.3)
*
new
*
or
*
print
*
private
*
protected
*
public
*
require
*
require_once
*
return
*
static
*
switch
*
throw
*
trait
(as of PHP 5.4)
*
try
*
unset()
*
use
*
var
*
while
*
xor
*
yield
(as of PHP 5.5)
*
yield from
(as of PHP 7.0)
Basic language constructs
PHP generally follows
C syntax
The syntax of the C programming language is the set of rules governing writing of software in C. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively ...
, with exceptions and enhancements for its main use in
web development
Web development is the work involved in developing a website for the Internet (World Wide Web) or an intranet (a private network). Web development can range from developing a simple single static page of plain text to complex web applications, ...
, 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
The backslash is a mark used mainly in computing and mathematics. It is the mirror image of the common slash (punctuation), slash . It is a relatively recent mark, first documented in the 1930s. It is sometimes called a hack, whack, Escape c ...
is supported as an
escape character
In computing and telecommunications, an escape character is a character that invokes an alternative interpretation on the following characters in a character sequence. An escape character is a particular case of metacharacters. Generally, the ...
. 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
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
coding style, with classes denoted by the
class
keyword. Functions defined inside classes are sometimes called
method
Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
s.
Control structure
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
s include:
if
,
while
,
do/while
,
for
,
foreach
, and
switch
. Statements are terminated by a semicolon, not line endings.
Delimiters
The PHP processor only parses code within its
delimiter
A delimiter is a sequence of one or more Character (computing), characters for specifying the boundary between separate, independent regions in plain text, Expression (mathematics), mathematical expressions or other Data stream, data streams. An ...
s. 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 file
A binary file is a computer file that is not a text file. The term "binary file" is often used as a term meaning "non-text file". Many binary file formats contain parts that can be interpreted as text; for example, some computer document files ...
s 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
Extensible HyperText Markup Language (XHTML) is part of the family of XML markup languages which mirrors or extends versions of the widely used HyperText Markup Language (HTML), the language in which Web pages are formulated.
While HTML, pr ...
and other XML
Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing data. It defines a set of rules for encoding electronic document, documents in a format that is both human-readable and Machine-r ...
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.
Non-recommended tags
Other delimiters can be used on some servers, though most are no longer supported. Examples are:
* "
" 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)
Variables and comments
Variables are prefixed with a dollar symbol and a type
Type may refer to:
Science and technology Computing
* Typing, producing text via a keyboard, typewriter, etc.
* Data type, collection of values used for computations.
* File type
* TYPE (DOS command), a command to display contents of a file.
* ...
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. As in C, variables may be cast
Cast may refer to:
Music
* Cast (band), an English alternative rock band
* Cast (Mexican band), a progressive Mexican rock band
* The Cast, a Scottish musical duo: Mairi Campbell and Dave Francis
* ''Cast'', a 2012 album by Trespassers William ...
to a specific type by prefixing the type in parentheses. PHP treats newline
A newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in character encoding specifications such as ASCII, EBCDIC, Unicode, etc. This character, or ...
s as whitespace
White space or whitespace may refer to:
Technology
* Whitespace characters, characters in computing that represent horizontal or vertical space
* White spaces (radio), allocated but locally unused radio frequencies
* TV White Space Database, a m ...
, in the manner of a free-form language. The concatenation
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalizations of concatenati ...
operator is .
(dot). Array elements are accessed and set with square brackets in both associative array
In computer science, an associative array, key-value store, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In math ...
s 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. 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.
Simplest program
The usual " Hello World" code example for PHP is:
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
="Hello World!"?>
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
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic opera ...
, comparison operators, error control operators, execution operators, increment/decrement operators, logical operators, string operators, array operators, conditional assignment operators.
Control structures
Conditionals
If ... else statement
The syntax of a PHP if ... else statement is as follows:
if (condition) elseif (condition2) else
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();
Ternary conditional operator
$abs = $value >= 0 ? $value : -$value;
/* Equivalent to */
if ($value >= 0) else
= Elvis operator
=
Since PHP 5.3 supports ''Elvis operator'' (?:
) in which it is possible to omit the middle part of the ternary operator.
$c = $a ?: $b;
/* Equivalent to */
$c = $a ? $a : $b;
= Null coalescing operator
=
Since version 7.0 PHP also supports Null coalescing operator
The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as (in alphabetical order): C# since version 2.0, Dart since version 1.12.0, PHP since versi ...
(??
).
$a = $b ?? $c;
/* Equivalent to */
$a = isset($b) ? $b : $c;
Since version 7.4 PHP also supports ''Null coalescing operator'' with the ??=
syntax.
$a ??= $b;
/* Equivalent to */
$a = $a ?? $b;
= Safe navigation operator
=
Since version 8.0 PHP also supports Safe navigation operator
In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator, null-propagation operator) is a binary operator that returns null if its first argument is null; ...
(?->
).
$variable = $object?->method();
/* Equivalent to */
$variable = $object ! null ? $object->method() : null;
Switch statement
An example of the syntax of a PHP switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function ...
is as follows:
switch (expr)
Note that unlike in C, values in case statement can be any type, not just integers.
Match expression
PHP 8 introduces the expression. The match expression is conceptually similar to a statement and is more compact for some use cases.
statements are traditionally favored for simple value-based comparisons, statements provide more flexibility and readability, particularly when using in complex conditions or patterns
echo match (1) ;
//> Bar
Loops
For loop
The PHP syntax of a for loop
In computer science, a for-loop or for loop is a control flow Statement (computer science), statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfi ...
is as follows:
for (initialization; condition; afterthought)
While loop
The syntax for a PHP while loop
In most computer programming languages, a while loop is a control flow Statement (computer science), statement that allows code to be executed repeatedly based on a given Boolean data type, Boolean condition. The ''while'' loop can be thought o ...
is as follows:
while (condition)
Do while loop
The syntax for a PHP do while loop
In many computer programming Programming language, languages, a do while loop is a control flow Statement (computer science), statement that executes a block of code and then either repeats the block or exits the loop depending on a given Boolea ...
is as follows:
do while (condition);
For each loop
The syntax for a PHP for each loop is as follows:
foreach ($set as $value)
Alternative syntax for control structures
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. Mixing syntax styles within the same control block is not supported. An example of the syntax for an if
/elseif
statement is as follows:
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:
'Thursday'): ?>
Tomorrow is Friday!
'Friday'): ?>
TGIF
ugh
Exception handling
Runtime exception handling method in PHP is inherited from C++.
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
Data types
Scalar types
PHP supports four scalar types: bool
, int
, float
, string
.
Boolean
PHP has a native Boolean type, named "bool
", similar to the native Boolean types in Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true
and zero as false
, as in Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
.
Both constants true
and false
are case-insensitive.
Integer
PHP stores whole numbers in a platform-dependent range. This range is typically that of 32-bit or 64-bit signed integers. Integer variables can be assigned using decimal (positive and negative), octal
Octal (base 8) is a numeral system with eight as the base.
In the decimal system, each place is a power of ten. For example:
: \mathbf_ = \mathbf \times 10^1 + \mathbf \times 10^0
In the octal system, each place is a power of eight. For ex ...
, hexadecimal
Hexadecimal (also known as base-16 or simply hex) is a Numeral system#Positional systems in detail, positional numeral system that represents numbers using a radix (base) of sixteen. Unlike the decimal system representing numbers using ten symbo ...
, and binary notations.
$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)
Float
Real numbers
In mathematics, a real number is a number that can be used to measurement, measure a continuous variable, continuous one-dimensional quantity such as a time, duration or temperature. Here, ''continuous'' means that pairs of values can have arbi ...
are also stored in a platform-specific range. They can be specified using floating point
In computing, floating-point arithmetic (FP) is arithmetic on subsets of real numbers formed by a ''significand'' (a signed sequence of a fixed number of digits in some base) multiplied by an integer power of that base.
Numbers of this form ...
notation, or two forms of scientific notation
Scientific notation is a way of expressing numbers that are too large or too small to be conveniently written in decimal form, since to do so would require writing out an inconveniently long string of digits. It may be referred to as scientif ...
.
$a = 1.234;
$b = 1.2e3; // 1200
$c = 7E-5; // 0.00007
$d = 1_234.567; // as of PHP 7.4.0
String
PHP supports strings
, which can be used with single quotes, double quotes, nowdoc or heredoc syntax.
Double quoted strings support variable interpolation:
$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
Special types
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. 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.
Compound types
PHP supports four compound types: array
, object
, callable
, iterable
.
Array
Arrays can contain mixed elements of any type, including resources, objects. Multi-dimensional arrays are created by assigning arrays as array elements. PHP has no true array type. PHP arrays are natively sparse and associative
In mathematics, the associative property is a property of some binary operations that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replacement for express ...
. Indexed arrays are simply hashes using integers as keys.
Indexed array:
$season = Autumn", "Winter", "Spring", "Summer"
echo $season // Spring
Associative array:
$salary = 34000, "Bill" => 43000, "Jim" => 28000">Alex" => 34000, "Bill" => 43000, "Jim" => 28000
echo $salary Bill" // 43000
Multidimensional array:
$mark = [
"biology" => 73,
"history" => 85
"> "Alex" => [
"biology" => 73,
"history" => 85
"Jim" => [
"biology" => 86,
"history" => 92
]
];
echo $mark["Jim"]["history"]; // 92
Object
The object
data type is a combination of variables, functions and data structures in the object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
paradigm.
class Person
{
//...
}
$person = new Person();
Callable
Since version 5.3 PHP has first-class function
In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
s that can be used e.g. as an argument to another function.
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
Iterable
Iterable
type indicate that variable can be used with foreach
loop. It can be any array
or generator
or object that implementing the special internal Traversable
interface.
function printSquares(iterable $data)
{
foreach ($data as $value) {
echo ($value ** 2) . " ";
}
echo "\n";
}
// array
$array = , 2, 3, 4, 5, 6, 7, 8, 9, 10
// generator
$generator = function (): Generator {
for ($i = 1; $i <= 10; $i++) {
yield $i;
}
};
// object
$arrayIterator = new ArrayIterator( , 2, 3, 4, 5, 6, 7, 8, 9, 10;
printSquares($array); // 1 4 9 16 25 36 49 64 81 100
printSquares($generator()); // 1 4 9 16 25 36 49 64 81 100
printSquares($arrayIterator); // 1 4 9 16 25 36 49 64 81 100
Union types
Union types were introduced in PHP 8.0
function foo(string, int $foo): string, int {}
Functions
PHP has hundreds of base functions and thousands more from extensions. Prior to PHP version 5.3.0, functions are not first-class function
In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
s 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.
Named arguments
Named arguments were introduced in PHP 8.0
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
Type declaration
Specifying the types of function parameters and function return values has been supported since PHP 7.0.
Return type declaration:
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
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
Anonymous functions
PHP supports true anonymous functions as of version 5.3. In previous versions, PHP only supported quasi-anonymous functions through the create_function()
function.
$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
Closures
Сreating closures
$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
PHP
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
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
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
A handle is a part of, or an attachment to, an object that allows it to be grasped and object manipulation, manipulated by hand. The design of each type of handle involves substantial ergonomics, ergonomic issues, even where these are dealt wi ...
, and not by value. PHP 5 introduced private and protected member variable
In object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called ...
s and methods, along with abstract classes and final classes as well as abstract method
A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be u ...
s 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
In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
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. Object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an a ...
s implementing ArrayAccess can be used with array syntax and object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an a ...
s implementing Iterator
In computer programming, an iterator is an object that progressively provides access to each item of a collection, in order.
A collection may provide multiple iterators via its interface that provide items in different orders, such as forwards ...
or IteratorAggregate can be used with the foreach language construct
In computer programming, a language construct is "a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of the programming language", as defined by in the ISO/IEC 2382 stan ...
. The static method and class variable
In class-based, object-oriented programming, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist.
A class variable is not an instance variable. It is a special t ...
features in Zend Engine 2 do not work the way some would expect. There is no virtual table
In computer programming, a virtual method table (VMT), virtual function table, virtual call table, dispatch table, vtable, or vftable is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding).
Wh ...
feature in the engine, so static variable
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s 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
A replica is an exact (usually 1:1 in scale) copy or remake of an object, made out of the same raw materials, whether a molecule, a work of art, or a commercial product. The term is also used for copies that closely resemble the original, without ...
of the source object and only override properties that need to be changed.
Traits
See also
* HTML
Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets ( ...
(Hypertext Markup Language)
* Web template system
A web template system in web publishing allows web designers and developers to work with ''web templates'' to automatically generate custom web pages, such as the results from a search. This reuses static web page elements while defining dynami ...
References
{{PHP, state=expanded
Programming language syntax
PHP software