This is a field guide to PHP.

This field guide shows PHP’s language constructs and syntax in a valid script with comments. Each feature has an expansible explanation tab. Most of these are linked to the relevant PHP manual page. These examples can be copied and pasted directly into code.

  1. <?php // PHP TagThis is a PHP tag, the “open” tag. It tells the server’s PHP engine to treat the following instructions as PHP.

  2. namespace Example {}; // DELETE THIS LINE BEFORE RUNNING Namespace DeclarationThis is the “namespace” keyword.

    Namespaces allow identically named definitions to exist in the same scope, as the PHP engine prepends the namespace string to the definition.

    Namespaces do not affect constants being defined with the “define” statement.

    If used, a namespace must be the first statement in a script (except for the “declare” statement).

    Namespaces can be declared without bracket syntax as well – namespace Example – followed by code within the namespace.

    No PHP code may exist outside of the brackets except a “declare” statement.

  3. namespace Example\subExample {}; // DELETE THIS LINE BEFORE RUNNING Multiple Namespace Declaration

    This is a declaration of another namespace – in this case, a sub-namespace. Multiple namespaces can be declared in a single script.

    Namespaces can be declared without bracket syntax as well – namespace Example – followed by code within the namespace.p>No PHP code may exist outside of the brackets except a “declare” statement.

  4. namespace {}; // DELETE THIS LINE BEFORE RUNNING Global Namespace Declaration

    This is a declaration of a global namespace. Multiple namespaces can be declared in a single script.

    Namespaces can be declared without bracket syntax as well – namespace Example – followed by code within the namespace

    p>No PHP code may exist outside of the brackets except a “declare” statement.

  5. use Example\subExample as Example, Example\subExample; // DELETE THIS LINE BEFORE RUNNING Namespace Aliasing/ImportingThe “use” and “as” operators allows the PHP engine to alias namespaces for easier management.

    If no “as” value is specified, the last section of the namespace name is used.

    The “use” operator must be used in the outermost scope or inside namespace declarations.

  6. // Single-line comment // Single-Line CommentThis is a tag for a single-line comment. From this tag onward, everything on the line is usually disregarded by the PHP engine.

  7. #  Single-line comment // Single-Line CommentThis is a tag for a single-line comment. From this tag onward, everything on the line is usually disregarded by the PHP engine.

  8. /* Multi-line comment line 1, // Multi-Line Comment Opening TagThis is an opening tag for a multi-line comment. From this tag onward, everything is disregarded by the PHP engine until the closing tag.

  9.    and line 2.
  10. */ // Multi-Line Comment Closing TagThis is the ending tag for a multi-line comment.

  11. include "./example.php"; // DELETE THIS LINE BEFORE RUNNING SCRIPT “include” Language ConstructThis is a PHP language construct that includes and executes the specified file.

    The file is specified by its include path. For Linux machines, the include path has two modes:

    • Absolute: starting with a ‘/’ or a letter.
    • Local: starting with ‘.’ (current directory) or ‘..’ (parent directory).

    Multiple file paths can be included by separating them with a colon (in Linux).

    If the file is not found in the specified location, the PHP engine looks for it in the script’s current directory, then in the current working directory.

    If no file is found, the PHP engine produces a warning but keeps going.

    The included file inherits its caller’s scope variables, but its own class and function definitions are global for the lines after they are included.

    If the script has a return value, the “include” statement returns that value. Otherwise it returns “1” on inclusion success and “0” on inclusion failure.

    PHP has many other language constructs.

  12. require "./example.php"; // DELETE THIS LINE BEFORE RUNNING SCRIPT “require” Language ConstructThis is a PHP language construct that also includes and executes the specified file.

    It acts identically to the “include” statement, except the PHP engine produces a fatal error if the file is not found and stops.

  13. include_once "./example.php"; // DELETE THIS LINE BEFORE RUNNING SCRIPT “include_once” Language ConstructThis is a PHP language construct that also includes and executes the specified file.

    It acts identically to the “include” statement, except the PHP engine does nothing if the file has previously been included.

  14. require_once "./example.php"; // DELETE THIS LINE BEFORE RUNNING SCRIPT “require_once” Language ConstructThis is a PHP language construct that also includes and executes the specified file.

    It acts identically to the “require” statement, except the PHP engine does nothing if the file has previously been included.

  15. spl_autoload_register( function ( $className ) { // “spl_autoload_register” FunctionThis is a PHP function (part of the standard PHP library) that can automatically load classes more flexibly than “__autoload.”

  16. include 'class_directory/' . $className . '.php';
  17. });
  18. const CONSTANT1 = 1; // Constant DefinitionThis is a definition of a constant. This way also works inside a class definition.

  19. define( "CONSTANT2", 2); // Constant DefinitionThis is a definition of a constant. It is the generally accepted way to define a constant outside a class definition.

  20. $variable; // Variable DeclarationThis is a declaration of a variable. Since it is declared outside of a function, it is global.

  21. $variable = 2; // Value AssignmentThis is a assignment of a value to a variable with PHP’s assignment operator.

  22. $variableOneLine = 3; // One-line Declaration/AssignmentThis is a one-line variable declaration and assignment.

  23. $variable = $variableOneLine; // Variable AssignmentThis is a variable assignment from another variable.

  24. $variable=$variableOneLine; // Assignment (No Spaces)
  25. true; // Reserved WordThis is a variable assignment with one of PHP’s reserved words, the boolean value ‘true’. It and the boolean value ‘false’ are case-insensitive.

    There are six kinds of reserved words unavailable for general use:

  26. $GLOBALS; // Superglobal VariableThis is one of PHP’s nine superglobal variables. They are reserved, predefined, and global.

    They are:


  27. PHP_VERSION; // Predefined ConstantThis is a predefined constant.

    PHP has many predefined constants.

  28. E_ERROR; // Predefined Error ConstantThis is a predefined error constant.

    PHP has many predefined constants for errors.

  29. __DIR__; // Magic ConstantThis is a magic constant, whose value is determined by the context in which it is called.

    PHP has several magic constants:

    • __LINE__
    • __FILE__
    • __DIR__
    • __FUNCTION__
    • __CLASS__
    • __TRAIT__
    • __METHOD__
    • __NAMESPACE__

  30. $variable = true; // Boolean Primitive TypeThis is a variable assignment of boolean type.

    Boolean variables can have values of ‘true’ and ‘false.’ (Both of these values are predefined constants.)

    All type values evaluate to ‘true’ except:

    • Boolean: FALSE
    • Integer: 0
    • Float: 0.0
    • String: "" and "0"
    • Array: array with zero elements
    • Object: object with zero member variables (PHP 4 only)
    • Object: SimpleXML object created from empty tags
    • Null: NULL

  31. $variable = 4; // Integer Primitive TypeThis is a variable assignment of integer type.

    Integers can be formatted:

    • Decimally: $a = 123
    • Positively: $a = +123
    • Negatively: $a = -123
    • Compoundedly: $a = +-+- 123
    • Octally: $a = 0123
    • Hexadecimally: $a = 0x123
    • Binarily: $a = 0b123

    Any variable that can be cast as an integer can be positive or negative.

  32. $variable = 5.1; // Floating Point Primitive TypeThis is a variable assignment of floating point (or double, or real number) type.

    Use the function is_nan($variable) to check if a floating point variable is a number.


  33. $variable = "hello"; // String Primitive TypeStrings are discussed in more detail further in the guide.

  34. $variable = array(); // Array Primitive TypeArrays are discussed in more detail further in the guide.

  35. $variable = mysql_connect('localhost', 'mysql_user', 'mysql_pass'); // DELETE THIS LINE BEFORE RUNNING SCRIPT Resource Primitive TypeThis is a variable assignment of resource type.

    Resources are variables that hold a reference to an external data source.

  36. $variable = call_user_func( 'exampleFunction' ); // Callback/Callable TypeThis is a variable assignment of callable type.

    Callables/Callbacks are functions that can be passed as a parameter.

    There are several varieties:

    • Statically: call_user_func( 'ExampleClass', 'staticMethod' );
    • Statically: call_user_func( 'ExampleClass::staticMethod' );
    • Inheritance: call_user_func( 'ExampleClassExtended', 'ExampleClass::staticMethod' );
    • From object: call_user_func( $exampleInstance, 'method' );
    • From object implementing __invoke(): call_user_func( $exampleInstance, 'hello' );
    • From closure: exampleFunction( $exampleClosure, $variable);

  37. $variable = new stdClass(); // Object Primitive TypeThis is a variable assignment of object type.

  38. $variable = null; // Null Primitive TypeThis is a variable assignment of null type.

    It sets the variable to the value of the constant NULL.

    There are three ways to declare a variable null:

    • assign it the NULL constant.
    • set no value for it.
    • use the unset function.

    Null is case-insensitive: NULL, null, and nULl are equivalent. NULL is conventional, as with all constants.

  39. $emptyArray = array(); // Empty Array DeclarationThis is a declaration and assignment of an empty array variable.

  40. $emptyArray = []; // Empty Array DeclarationThis is also a declaration and assignment of an empty array variable.

  41. $populatedArray[] = 1; // Populated Array DeclarationThis is a shorthand declaration and assignment of an array variable populated with a single element.

    This array contains one integer element with an automatic numeric index. The index starts at 0.

  42. $populatedArray = array( 2, 3, 4 ); // Populated Array DeclarationThis is a declaration and assignment of an populated array variable.

    This array contains three integers with an automatic numeric index. The index starts at 0.

  43. $populatedArray = [ 5, 6, 7 ]; // Populated Array DeclarationThis is also a declaration and assignment of an populated array variable.

  44. $populatedArray = array( // Multiline Populated Array DeclarationThis is a multiline declaration and assignment of an populated array variable.

  45. 8,
  46. "nine", // Different Element TypeArrays can hold many types of data, even other arrays.

  47. 10
  48. ); // End-of-Array Identifier
  49. $populatedArray = array( // Key-Value Array AssignmentThis is a declaration and assignment of an array with mixed integer/string keys.

    Each key accesses a single element in the array. The array is still iterable, even if gaps in a key sequence exist or some of the keys are strings.

    Keys are optional. If none is explicitly provided, the PHP engine increments the highest integer key and uses that value.

    Valid types for array keys include:

    • Integers
    • Floats: cast to integers and truncated
    • Bools: cast to integers (0, 1)
    • Null: cast to an empty string: ""

    Arrays and objects are not valid keys.

  50. 11 => "twelve", // Integer Key-Value AssignmentThe key value of 10 is an integer.

  51. "13" => "fourteen", // Integer Key-Value AssignmentThe key value of “13” will evaluate to an integer.

  52. "fifteen" => array( "sixteen", "seventeen", "eighteen" ), // String Key-Value AssignmentThe key value of “fifteen” remains a string.

  53. "nineteen" // Value AssignmentNot every value in an array requires a key.

  54. );
  55. $populatedArray[14]; // Element AccessThis syntax accesses a single element in an array.

  56. $populatedArray{14}; // Element AccessThis syntax also accesses a single element in an array.

  57. $populatedArray["twenty"] = 21; // Element CreationThis syntax also creates a single element in an array if the specified key does not exist.

  58. $populatedArray[] = 22; // Element CreationThis syntax creates a single element in an array if the specified key does not exist.

    If the key value to be accessed or created is not specified, the PHP engine increments the highest integer key and uses that value.

  59. $uninterpretedString = 'hello1\n'; // Uninterpreted String DeclarationThis is a declaration of a string variable. Single quotes mean the string is taken literally – variables and most escape sequences are not valid. Only the escape sequences ‘\'’ and ‘\\’ will output as single characters. Newlines are parsed, but not the ‘\n’ escape sequence.

  60. $interpretedString = "hello2\n"; // Interpreted String DeclarationThis is a declaration of a string variable. Double quotes mean the string is interpreted/parsed. Named variables will be expanded. (Anything after a ‘$’ character will be taken as part of a variable name until the engine encounters a character not allowed for variable names.) Escape sequences will be be interpreted.

  61. $complexString = "{$interpretedString}hello2\n"; // Complex Escape SyntaxAnything between the opening and closing curly brackets will be treated the same as it would be outside the string.

  62. $nowdocString = <<<'ENDID' // DELETE THIS COMMENT AND ALL EXTRANEOUS CHARACTERS ON THIS LINE Nowdoc String DeclarationThis is an opening nowdoc identifier. Text between this line and a line consisting solely of the heredoc identifier and a semi-colon will be treated as single-quoted text.

  63. This will echo the following text literally: $interpretedString.
  64. ENDID; // DELETE THIS COMMENT AND ALL EXTRANEOUS CHARACTERS ON THIS LINE End-of-Nowdoc IdentifierThis is the closing nowdoc identifier. Text on this line and after will not be added to the string. It must exist alone on a line with a semi-colon and no indenting spaces. It must be preceded by a newline character.

  65. $heredocString = <<<ENDID // DELETE THIS COMMENT AND ALL EXTRANEOUS CHARACTERS ON THIS LINE Heredoc String DeclarationThis is an opening heredoc identifier. Text between this line and a line consisting solely of the heredoc identifier and a semi-colon will be treated as double-quoted, interpreted text.

  66. This will echo the string contents: $interpretedString.
  67. ENDID; // DELETE THIS COMMENT AND ALL EXTRANEOUS CHARACTERS ON THIS LINE End-of-Heredoc IdentifierThis is the closing heredoc identifier. Text on this line and after will not be added to the string. It must exist alone on a line with a semi-colon and no indenting spaces. It must be preceded by a newline character.

  68. $interpretedString[0]; // Character AccessThis syntax accesses a single character in a string, like an element in an array.
  69. $interpretedString{0}; // Character AccessThis syntax also accesses a single character in a string to be accessed, like an element in an array.
  70. $concatenatedString = $complexString . "hello3\n"; // String Concatenation OperatorThis operator will join two strings in a single variable with the same precedence as a “+” operator.

  71. $concatenatedString .= "hello4\n"; // String Concatenation OperatorThis operator will join two strings in a single variable with the same precedence as a “+” operator.

  72. $variable + $variable; // Arithmetic OperatorThis is one of PHP’s arithmetic operators.

    There are eight:

    • Identity: +$a
    • Negation: -$a
    • Addition: $a + $b
    • Subtraction: $a – $b
    • Multiplication: $a * $b
    • Division: $a / $b
    • Modulus: $a % $b
    • Exponentiation: $a ** $b

    The identity, or unary plus, operator, does nothing except convert variables to the integer or double type, as appropriate.

    PHP also offers many built-in mathematics functions.

  73. $variable & $variableOneLine; // Bitwise OperatorThis is one of PHP’s bitwise operators. They return the value of operation on two variables.

    There are six:

    • And: $a & $b
    • Or: $a | $b
    • Xor: $a ^ $b
    • Not: ~ $a
    • Shift left by $b steps: $a << $b
    • Shift right by $b steps: $a >> $b

  74. $variable = 4; // Assignment OperatorThis is one of PHP’s assignment operators.

    PHP also has combined assignment operators:

    • Arithmetic:
      • Addition: $a += $b
      • Subtraction: $a -= $b
      • Multiplication: $a *= $b
      • Division: $a /= $b
      • Modulus: $a %= $b
      • Exponentiation: $a **= $b
    • String:
      • Concatenation: $a .= $b
    • Array:
      • Key-value: $a => $b
    • Bitwise:
      • And: $a &= $b
      • Or: $a |= $b
      • Xor: $a ^= $b
      • Shift left by $b steps: $a <<= $b
      • Shift right by $b steps: $a <<= $b

  75. $variable == $variableOneLine; // Comparison OperatorThis is one of PHP’s comparison operators.

    There are twelve:

    • Equal (loose comparison): $a == $b
    • Identical (strict comparison): $a === $b
    • Not equal: $a != $b
    • Not equal: $a <> $b
    • Not identical: $a !== $b
    • Less than: $a < $b
    • Greater than: $a > $b
    • Less than or equal to: $a >= $b
    • Greater than or equal to: $a <= $b
    • Spaceship: $a <=> $b
    • Null coalesce: $a ?? $b ?? $c

    These operators typically return ‘true’ if the comparison is true, and ‘false’ if the comparison is false.

    The last two operators are only available in PHP 7 and return more than ‘true’ or ‘false’.

    The twelfth operator is a ternary operator, which has a line of its own in this guide.

  76. (true) ? $variable : $variableOneLine; // Ternary OperatorThis is a ternary comparison operator.

    It is shorthand for an if/else statement for the object in parentheses. It performs the first statement if the object evaluates to true, the second if it does not.

  77. @$emptyArray["invalidKey"]; // Error Control OperatorThis is an error control operator. It suppresses PHP-generated error messages, including fatal error messages.

    If the track error feature is turned on, the most recent error message will be written to the $php_errormsg reserved variable.

  78. `cd ../\nls -al`; // Execution OperatorThis is an execution operator.

    It executes the text between the backslashes as a shell command and returns the output.

  79. $variable++; // Increment/Decrement-ing OperatorThis is one of PHP’s incrementing operators. They can operate on strings or numbers.

    There are four:

    • Pre-increment: ++$a
    • Post-increment: $a++
    • Pre-decrement: --$a
    • Post-increment: $a--

  80. $variable and $variableOneLine; // Logical OperatorsThis is one PHP’s logical operators. They return the combined boolean value of the boolean inputs, unlike the bitwise operators.

    There are six:

    • And: $a and $b
    • Or: $a or $b
    • Xor: $a xor $b
    • Not: !a
    • And (high precedence) : $a && $b
    • Or (high precedence): $a || $b

  81. $variable instanceof ExampleClass; // Instanceof Type OperatorThis is PHP’s instanceof type operator. It returns true if the object is an instance of the class; otherwise it returns false.

  82. (bool) $variable; // Casting Type OperatorThis is one of PHP’s other casting operators. It converts the object into an instance of the object or primitive type.

    There are seven:

    • Integer: (integer), (int)
    • Boolean: (boolean), (bool)
    • Float: (double), (float), (real)
    • String: (string)
    • Array: (array)
    • Object: (object)
    • null: (unset)

    Note: casting an array as an object will create an object of the predefined stdClass, with array values becoming properties and non-numeric keys becoming property names.

    Note: casting an object as an array will create an array, with properties becoming array elements. Private properties have the class name prepended to the element key. Protected properties have “*” prepended to the element key. Both of these prepensions are surrounded by null bytes: “\0”

    Using the settype() function serves a similar purpose.

    Converting a string value to a number will only convert the numbers left of an invalid numeric character.

    The Type Conversion Table shows the valid casting.

  83. $emptyArray + $populatedArray; // Array OperatorThis is one of PHP’s array operators.

    There are six:

    • Union: $a + $b
    • Equal: $a == $b
    • Identical: $a === $b
    • Not equal: $a != $b
    • Not equal: $a <> $b
    • Not identical: $a !== $b

    The first returns the union of the two arrays. The others return ‘true’ if the comparison is true, and ‘false’ if the comparison is false.

  84. $variableReference = &$variable; // Reference OperatorThis is one PHP’s reference operator.

    The reference operator allows a news variable to refer to variable contents already referenced by another variable name. They are, essentially, aliases.

  85. $populatedArray = [1, 2, 3 => 4]; // Other OperatorsThese are some of PHP’s more obscure operators.

    They include:

    • Commas: ,
    • Array brackets: []
    • Key-value assignment: =>
    • Clone: clone
    • New: new
    • Static property: ::
    • Object property (arrow): ->
    • Class: extends, implements

    Arrays are discussed in more detail further and previously in this guide.

  86. $variableOperatorPrecedence = 1 - 2 + 3 / 4 * 5 ** 6; // Operator PrecedenceOperators are performed in order of precedence.

    This is a high-level ranking of precedence:

    • clone new
    • [
    • **
    • ++ -- ~
    • instanceof
    • !
    • * / %
    • + - .
    • << >>
    • < <= > >=
    • == != === !=== <>
    • &
    • ^
    • |
    • &&
    • ||
    • ?:
    • = += -= *= **= /= .= %= &= |= ^= <<= >>= =>
    • and
    • xor
    • or
    • ,

  87. if( $variable == 0 ) { // “if” StatementThis statement is a PHP control structure language construct that executes the statement between the brackets if the statement between the parentheses evaluates to “true.”

  88. $variable++;
  89. } // “if” Statement Closing Tag
  90. if( $variable == 1 ) { $variable++; } // Single-Line “if” StatementEvaluation and execution of many control structure language constructs can occur on the same line.
  91. elseif( $variable == 2 ) { $variable++; } // “elseif” Statement

    This statement is a PHP control structure language construct that executes the statement between the brackets if:

    • the control structure statement immediately previous to it has evaluated to false and not executed, and
    • the statement between its parentheses evaluates to “true.”

  92. else if( $variable == 4 ) { $variable++; } // “else” “if” StatementsThis statement is an amalgamation of a shorthand “else” statement followed by an if statement. It is functionally identically to “elseif,” but slightly slower.

  93. else { $variable++; } // “else” Statement

    This statement is a PHP control structure language construct that executes the statement between the brackets only if:

    • the control structure statement immediately previous to it has evaluated to false.

  94. switch( $variable ) { // “switch” StatementThis statement is a PHP control structure language construct that executes the statement inside the parentheses, then evaluates it against the cases that follow.

    If any case value is loosely equal to the statement, all further statements in the structure are executed until the structure ends or the PHP engine encounters a “break” or “continue” statement.

    Though similar in effect to a series of “if” statements, the evaluating statement for a switch statement is evaluated only once.

  95. case 0: // Case StatementThis statement is a PHP control structure language construct that instructs the PHP engine to evaluate its value against the evaluating statement.

    If the value is loosely equal (e.g., if “$a == $b”), the PHP engine begins executing.

  96. $variable++;
  97. break; // “break” StatementThis statement ends the switch control structure execution. “continue” would also end it in this case.

    “switch” and “continue” statements are discussed in more detail further in this guide.

  98. case "a"; // Case Statement with Semi-ColonCase statements may be ended with semi-colons instead of colons.
  99. $variable++;
  100. default: // “default” StatementThis statement is a PHP control structure language construct that instructs the PHP engine to begin executing regardless of the evaluating statement.
  101. $variable++;
  102. }
  103. while( $variable < 10 ) { $variable++; } // “while” StatementThis statement is a PHP control structure language construct that executes the statement between the brackets “while” the statement between parentheses evaluates to “true.”

    Evaluation occurs before execution.

  104. do{ $variable++; } while( $variable < 20 ); // “do-while” StatementThis statement is a PHP control structure language construct that executes the statement between the brackets “while” the statement between parentheses evaluates to “true.”

    Evaluation occurs after execution.

  105. for( $i = 0; $i++; $i < 10 ) { $variable++; } // “for” StatementThis statement is a PHP control structure language construct that executes the statement between the brackets “for” each iteration that the second expression between parentheses is true.

    The following sequence occurs:

    • The first expression is executed before the first iteration of the loop.
    • The second expression is evaluated. The loop iteration executes only if it is “false”.
      • The statement between the brackets is executed.
      • The third expression is executed.
      • The PHP engine returns to the evaluation of the second expression.

    Multiple expressions, separated by commas, may exist in each expression. The loop execution and iteration depends only on the “true”/”false” condition of the last second expression.

    All expressions may be empty as long as the semi-colons remain, in which case the loop runs perpetually.

  106. foreach( $populatedArray as $elementValue ) { $elementValue++; } // “foreach” StatementThis statement is a PHP control structure language construct that executes the statement between the brackets “foreach” of the elements of an array.

    Passing $elementValue in as a reference – &$elementValue – allows the element to be modified.

    Use the unset() function to destroy the last reference to $element, as it is not destroyed or overwritten at the end of the loop.

    When applied to objects, “foreach” statements iterate through their public properties.

  107. foreach( $populatedArray as $elementKey => $elementValue ) { $elementValue++; } // “foreach” Statement (Key-Value)This statement is a foreach statement that loops through an array and provides both keys and values.
  108. foreach( $populatedArray as list( $elementValue ) ) { $elementValue++; } // “foreach” Statement (List)This statement is a foreach statement that loops through an array and converts each element to a list.

    If the list has fewer items than the sub-array, only the first are returned. If the list has more items than the sub-array, an “undefined offset” notice is returned.

  109. for( $i = 0; $i < 10; $i++ ) {
  110. break; // “break” StatementThis statement is a PHP control structure language construct. It stops execution of the loop structure.

    It stops:

    • for
    • foreach
    • while
    • do-while
    • switch

  111. break 1; // “break” Statement with Parameter“break” statements also accept an optional parameter telling it out of how many layers of loop to break. This parameter must be numeric, greater than 0, and not greater than the number of nested loops.
  112. continue; // “continue” StatementThis statement is a PHP control structure language construct. It stops execution of the current iteration of the loop and moves on to the next one.

    It stops:

    • for
    • foreach
    • while
    • do-while
    • switch

    “continue” statements can use numeric parameters just like “break” statements.

  113. }
  114. if( $variable == true ) // Alternate Control Structure SyntaxThis is a shorthand way to express some control structure statements. If the statement between parentheses is true, the statement immediately following executes.

    Statements executed as part of control structure language construct evaluations don’t count towards this immediacy. Thus, “else if( $variable == 4 ) {$variable++}” is valid.

    Seven control structures can use this syntax:

    • if
    • else
    • elseif
    • while

  115. echo $variable;
  116. if( $variable == true ): // Alternate Control Structure SyntaxThis is another way to express some control structure statements. If the statement between parentheses is true, the all lines before the closing statement “endif” execute.

    Seven control structures can use this syntax:

    • if/endif
    • else
    • elseif
    • while/endwhile
    • for/endfor
    • foreach/endforeach
    • switch/endswitch

    Mixing syntaxes in the same control block causes a fatal error.

  117. echo $variable;
  118. endif; // Alternate Control Structure Syntax Closing
  119. declare(ticks=1) { $variable++; }; // “declare” Language ConstructThis is a language construct sets execution directives for the PHP engine.

    Only two directives exist right now:

    • Ticks: ticks are events that occur when the PHP engine performs low-level statements while executing coded statements in the “declare” block. That event can be defined by the register_tick_function() function.
    • Encoding: encoding refers to the script’s encoding scheme.

    The “declare” construct allows for parameters: e.g., “declare(ticks=1)” and “declare(encoding="ISO-8859-1")”.

    Only literals are allowed as parameters: “1” and “ISO-8859-1” are allowable, but $variable or CONSTANT1 are not.

    The brackets are optional. If they are omitted, the directive applies globally after its declaration within the current file and child files (but not parents).

  120. goto goToTarget; // “goto” Language ConstructThis is a PHP language construct that sends the PHP engine to the targeted location in the code.

    The location must be in the same file and scope as the construct.

    Failure to specify a valid location or non-string literal results in a fatal error.

    Placing your “goto” target above the command may create an infinite loop.

  121. goToTarget: // “goto” TargetThis is the “goto” target. Goto commands for this target will “go to” this point and begin executing.

  122. return $variable; // DELETE THIS LINE BEFORE RUNNING SCRIPT “return” Language ConstructThis is a PHP language construct that returns the PHP engine to the scope from which it is called.

    If called within a function, it ends that function’s execution and returns the value passed in its argument.

    If no argument is passed, “return” returns NULL.

    If called within an eval() statement or script file, it ends execution of that statement or file.

    If called within the global scope (as here), it ends execution of its current script file.

    If that script file was included or required as part of a parent file, the PHP engine returns to execution of that parent file.

    If that script file is automatically pre- or appended by configuration options in php.ini, executed is stopped globally.

  123. exit; // DELETE THIS LINE BEFORE RUNNING SCRIPT “exit” Language ConstructThis is a PHP language construct that stops script execution by the PHP engine entirely.

    If supplied with a string parameter – e.g., “exit("hello");” – it will print that string before terminating.

    If supplied with an integer parameter between 0 and 254 – e.g., “exit(5);” – that integer will be used as an exit status.

    Unlike return, this stop is total.

  124. die; // DELETE THIS LINE BEFORE RUNNING SCRIPT “die” Language ConstructThis is a PHP language construct that stops script execution by the PHP engine entirely.

    If supplied with a string parameter – e.g., “die("hello");” – it will print that string before terminating.

    If supplied with an integer parameter between 0 and 254 – e.g., “exit(5);” – that integer will be used as an exit status.

    Unlike return, this stop is total.

  125. echo "hello"; // “echo” Language ConstructThis is a PHP language construct that outputs objects to text.

    It accepts multiple optional arguments, each separated by a comma.

  126. print "hello"; // “print” Language ConstructThis is a PHP language construct that outputs objects to text and returns 1.

  127. var_dump( "hello" ); // Output FunctionThis is a function that outputs objects to text with additional information.

  128. var_export( "hello" ); // Output FunctionThis is a function that outputs objects to text as valid PHP code.

  129. print_r( $emptyArray ); // Output Array FunctionThis is a function that outputs an array to text.

  130. unset( $populatedArray[15] ); // “unset” FunctionThis is a built-in function that sets the specified variable to the null type, destroying it.

  131. isset( $populatedArray ); // “isset” FunctionThis is a built-in function that determines if a variable is set and not NULL.

    The Type Comparison Table usefully distinguishes the results of these checks.

  132. is_null( $populatedArray ); // “is_null” FunctionThis is a built-in function that determines if a variable is NULL and not set.

    The Type Comparison Table usefully distinguishes the results of these checks.

  133. empty( $populatedArray ); // “empty” FunctionThis is a built-in function that determines if a variable is empty.

    A variable is empty if:

    • String: "" or '' or "0"
    • Integer: 0
    • Float: 0.0
    • NULL: NULL
    • Bool: FALSE
    • Array: array()
    • Variable: declared without a value

    The Type Comparison Table usefully distinguishes the results of these checks.

  134. if( $populatedArray ); // Boolean Casting “if” statementThis “if” statement checks the boolean value of a variable.

    The Type Comparison Table usefully distinguishes the results of these checks.

  135. get_defined_vars( $variable ); // “get_defined_vars” FunctionThis function retrieves all available variables in the function call’s scope.

    Similar functions are get_defined_functions() and get_defined_constants.

  136. gettype( $variable ); // “gettype” FunctionThis function returns the string representation of the primitive type of a variable.

  137. get_class( new ExampleClass ); // “get_class” FunctionThis function returns the string representation of the class of an object.

    The get_resource_type() function serves the same purpose for resources.

  138. boolval( $variable ); // “booValue” FunctionThis function returns the boolean value of a variable.

    Other functions like this are:

    Note: converting a string value to a number will only convert the numbers left of an invalid numeric character.

  139. is_bool( $variable ); // “is_bool” FunctionThis function checks if the function is of the array primitive type.

    It returns a boolean value: ‘true’ if yes, ‘false’ if no.

    Other functions like this are:

  140. explode( "\n", $concatenatedString ); // “explode” String FunctionThis function takes the second string parameter and separates it into array values based on the first string parameter.

  141. preg_split( '//', $concatenatedString ); // “reg_split” String FunctionLike explode, this function takes the second string parameter and separates it into array values.

    This split is determined by evaluating the first string parameter as a regular expression.

  142. implode( ",", $populatedArray ); // “implode” Array FunctionThis function takes an array concatenates it into a string, with the string parameter serving as glue.

    The string parameter is optional; its default value is “”.

    This is one of many useful array functions.

  143. sort( $populatedArray ); // “sort” Array FunctionThis function sorts an array.

    This is one of many useful array sorting functions.

    This is also one of many useful array functions.

  144. exampleFunction(); // User-Defined Function CallThis is a function call of a user-defined function.

    A function can be called earlier in the script than its creation, as long as its creation is not dependent on other actions in the script.

  145. parametersFunction( $variable, $variableOneLine ); // Function Call with ParametersThis is a function call with arguments (of a function with parameters).

    The arguments supplied must equal or exceed the parameters, unless some of them have default values.

  146. parametersFunction( $variable, function () {} ); // Function Call with Anonymous Function ParameterThis is a function call with one argument an anonymous function, or closure.

    A named closure, like $exampleClosure, could also be used.

  147. parametersFunction( ...$populatedArray ); // Function Call with Parameters (Alternate)This is a function call with arguments (of a function with parameters).

    Preceding an array or Traversable object with ” allows it to substitute for a list of parameters.

  148. $returnVariable = returnFunction(); // Function Call with ReturnThis is a function call with a return value assigned to a variable.

  149. $returnReference = returnReferenceFunction(); // Function Call with Reference ReturnThis is a function call with a return reference assigned to a variable.

  150. $functionName = 'exampleFunction';
  151. $functionName(); // Variable Function CallThis is a function call from a variable.

    This method is not available for language constructs like “echo”.

    The same method works for object properties, even static properties.

  152. \exampleFunction(); // Qualified Global Function CallThis is a function call for a function in the global namespace.

    If a function, variable, or constant does not exist in a namespace, PHP will look for it in the global space.

    This is a fully qualified function call.

  153. $exampleClosure(); // Closure CallThis is a function call from a closure definition.

  154. function exampleFunction() {} // Function DefinitionThis is a PHP function definition/prototype.

    This one takes no arguments (as it has no parameters) and returns no values.

    Function definitions allow functions to be called anywhere in their scope unless they are defined conditionally (e.g., within an “if” statement or within another function definition).

    Functions can be called recursively, but the script may break if called more than 200 times.

  155. function parametersFunction( $parameter1, $parameter2 ) {} // Function ParametersThis is a function definition with arguments.

  156. function referenceParameterFunction( &$parameter1 ) {} // Reference ParameterThis is a function definition with arguments passed by reference.

    The object used as an argument may be modified.

  157. function typeDefinitionFunction( ExampleClass $parameter ) {} // Type Declaration/HintThis is a function definition with type declaration.

    Type declarations are allowed for classes, arrays, and callables, but not yet bools, floats, ints, or strings.

    Type declarations can be for interfaces.

  158. function defaultParameterFunction( $parameter = "hello" ) {} // Default ParameterThis is a function definition with a parameter with a default value.

    The default value must be a constant value. All defaults should be on the right side of any non-defaults, or unexpected behavior may occur.

    Default parameter values are an excellent way of making optional parameters.

  159. function variableParameterFunction( ...$parameter ) {} // Varying ParametersThis is a function definition with a variable number of parameters.

  160. function oldVariableParameterFunction() { // Alternative Varying ParametersThis is a function definition with a variable number of parameters sometimes used before PHP 5.6.

  161. foreach( func_get_args() as $argument ) {} // “func_get_args” FunctionThis is a function for getting a function’s arguments as an array.

  162. }
  163. function returnFunction() {
  164. return "hello"; // Return ValueThis is a PHP return value.

    Return values can be of any primitive type. If no return statement is declared, the return type is NULL.

    To return multiple values, return an array.

    To return a reference, use the operator reference (“&”) in both the function definition (“function &a(){}”) and in the return value assignment (“$b = &a();”).

  165. }
  166. function &returnReferenceFunction() { // Return Reference ValueThis is a function that returns a reference value instead of a regular value.

  167. return "hello";
  168. }
  169. function exampleGenerator() { // Generator DeclarationA generator is an iterating function.

    It traverses a “foreach” (or loop) statement without building an array in memory.

    This results in a occasionally substantial memory and time savings.

    A generator function does not return a value, it yields many values.

  170. for( $i = 0; $i < 10; $i++ ) { yield "hello"; } // “yield” Language ConstructThe “yield” language construct acts like a return construct, except it can be called many times. Each time, it saves the current function state and suspends execution until it is called again.
  171. }
  172. $exampleClosure = function( $parameter ) { // Closure/Anonymous Function DeclarationThis is a declaration of a closure, or anonymous function.

    Closures are functions without a defined name.

    They are often used in callbacks.

  173. echo "Hello, $parameter";
  174. }; // End-of-Closure Identifier
  175. $exampleClosureInheriting = function( $parameter ) use ( $variable ) { // Closure InheritanceThis is a declaration of a closure that inherits a variable from its parent scope.

  176. echo "Hello, $parameter $variable";
  177. };
  178. trait exampleTrait { // Trait DeclarationThis is a declaration of a trait.

    Traits are collections of code, both methods and properties, that can be used inside classes. They allow a form of multiple inheritance.

    If a trait’s method’s name is identical to one defined by a class’s superclass, it overrides that method. If it is identical to one defined by the class itself, that overrides the trait’s method.

  179. function traitMethod() {} // Trait Method DeclarationThis is a declaration of a trait method.

    Trait methods can be static, abstract, and have visibility restrictions, just like an abstract class.

  180. public $traitProperty = 10; // Trait Property DeclarationThis is a declaration of a trait property.

    Trait properties should not have the same names as class properties.

  181. }
  182. trait exampleTrait2 {}
  183. trait exampleTrait3 {}
  184. trait exampleTrait4 {
  185. function traitMethod2() {}
  186. }
  187. trait exampleTrait5 {
  188. function traitMethod2() {}
  189. }
  190. class ExampleClass { // Class DefinitionThis is a declaration of a class.

  191. var $property = 4; // Property DeclarationThis is a declaration of a class variable/member variable/property. The “var” keyword declares variables to be public.

  192. public $publicProperty = 5; // Public Property DeclarationThis is a declaration of a public class variable/property. It is accessible anywhere from an instance of the class.

  193. protected $protectedProperty = 6; // Protected Property DeclarationThis is a declaration of a protected class variable/property. It is accessible only within instances of a class or instances of its parents or descendants.

  194. private $privateProperty = 7; // Private Property DeclarationThis is a declaration of a private class variable/property. It is accessible only within instances of a class.

  195. public static $staticProperty = 8; // Static Property DeclarationThis is a declaration of a static (and public) class variable/property. It is accessible without instantiating the class.

  196. const CLASSCONSTANT = 9; // Class Constant DeclarationThis is a declaration of a class constant. It is accessible without instantiating the class.

  197. function __construct() {} // Construct Magic Method DeclarationThis is a declaration of the __construct class function.

    The __construct magic method is called when the class is instantiated.

    The __construct method can have multiple parameters.

    Other PHP magic methods are:

  198. function __destruct() {} // Destruct Magic Method DeclarationThis is a declaration of the __destruct class function.

    The __destruct method is called when an object no longer has a reference or the PHP script is entering its shutdown sequence.

  199. function method() {} // Method DeclarationThis is a declaration of a class function. The lack of a visibility keyword means it is public.

  200. public function publicMethod() {} // Public Method DeclarationThis is a declaration of a public method/class function. It is accessible anywhere from an instance of the class.

  201. protected function protectedMethod() {} // Protected Method DeclarationThis is a declaration of a protected method/class function. It is accessible only within instances of a class or instances of its parents or descendants.

  202. private function privateMethod() {} // Private Method DeclarationThis is a declaration of a private method/class function. It is accessible only within instances of a class.

  203. public static function staticMethod() {} // Static Method DeclarationThis is a declaration of a static (and public) method/class function. It is accessible without instantiating the class.

  204. final public function finalMethod( $parameter1, $parameter2 ) {} // Final Method DeclarationThis is an keyword that prevents this method from being redefined by child classes.

    This keyword can also be applied to classes to prevent them from being extended.

  205. function fullMethod( $parameter1, $parameter2 ) {
  206. $this->property; // $this pseudo-variableThis is an accessing of the current object’s properties.

    “$this” is the appropriate keyword for non-static properties and methods.

  207. self::staticProperty; // Current Class PropertyThis is an accessing of the current class’s properties.

    “self” is the appropriate keyword for the current class’s static properties and methods and constants.

    “parent” is the appropriate keyword for the parent class’s static properties and methods and constants.

  208. self::staticMethod(); // Current Class Method
  209. static::staticMethod(); // Late Static BindingThis keyword makes methods refer to their calling class, rather than their defining class, when being called from child classes.

    Normally, static methods are called in the context of the class in which they are actually defined.

  210. return $functionProperty;
  211. }
  212. use exampleTrait; // “use” StatementThis is a statement that allows a class to use a trait.

  213. use exampleTrait2, exampleTrait3; // Multiple “use” StatementThis is a statement that allows a class to use multiple traits.

  214. use exampleTrait4, exampleTrait5 {
  215. exampleTrait4::traitMethod2 insteadof exampleTrait5; // “insteadof” OperatorThis is an operator that allows the PHP engine to decide which of two identically-named trait methods is to be used.

  216. exampleTrait5::traitMethod2 as private traitMethod3; // “as” OperatorThis is an operator that can rename trait methods and properties and change their visibility.

  217. }
  218. }
  219. class ExampleClassExtended extends ExampleClass { // Child Class DefinitionThis is a definition of a class that extends another class. It is the child of the parent class.

    Each class may extend only one parent.

  220. const CLASSCONSTANT = parent::CLASSCONSTANT;
  221. }
  222. abstract class ExampleClassAbstract { // Abstract Class DefinitionThis is a definition of an abstract class.

    An abstract class cannot be used to instantiate an object. Its child class definitions must define all its abstract functions with equal signatures and equal or greater visibility.

  223. const CONSTANTABSTRACT = "hello"; // Abstract Class ConstantConstants and static properties and methods do not require instantiation and thus may be called from an abstract class.

  224. static $staticPropertyAbstract = "hello"; // Abstract Class ConstantConstants and static properties and methods do not require instantiation and thus may be called from an abstract class.

  225. abstract function abstractMethod(); // Abstract Method DeclarationThis method must be defined in all concrete child class definitions.

  226. function concreteMethod() {} // Concrete Method DeclarationAn abstract class can also contact concrete method declarations that don’t need to be defined later.

  227. }
  228. class ExampleClassConcrete extends ExampleClassAbstract { // Concrete Class DefinitionThis is a definition of a class extended from an abstract class.

    It defines the required abstract method.

  229. function abstractMethod() {} // Concrete Method DeclarationAn abstract class can also contact concrete method declarations that don’t need to be defined later.

  230. }
  231. interface ExampleInterface { // Interface Method DeclarationThis is a declaration of an interface.

    Interfaces allow you to define the constants and methods of implementing classes.

    Interfaces can be extended like classes.

  232. const CONSTANTINTERFACE = "hello"; // Interface ConstantConstants do not require instantiation and thus may be called from an interface.

  233. function requiredMethod(); // Interface Method DeclarationThis is a declaration of an interface method.

    All implementing classes must define this method. All parameters must match, including types.

  234. }
  235. class ExampleClassImplemented implements ExampleInterface { // Implemented Class DeclarationThis is a declaration of a class that implements an interface.

    A class may implement multiple interfaces, as long as the interfaces don’t have a method with a shared name and different parameters.

  236. function requiredMethod() {} // Implemented Method Declaration
  237. }
  238. class ExampleClassIterator implements Iterator { // Iterator Class DeclarationThis is a declaration of a class that implements the iterator interface.

    By default, all of an object’s public properties can be accessed with a “foreach” statement. Implementing the iterator interface allows that to be refined.

  239. function rewind() {} // “rewind” functionThis is a declaration of a method that returns the iterator pointer to the first element.
  240. function current() {} // “rewind” functionThis is a declaration of a method that returns the current element.
  241. function key() {} // “rewind” functionThis is a declaration of a method that returns the key of the current element.
  242. function next() {} // “rewind” functionThis is a declaration of a method that moves the iterator pointer to the next element.
  243. function valid() {} // “rewind” functionThis is a declaration of a method that checks if the current value of the iterator pointer is valid.
  244. }
  245. $exampleInstance = new ExampleClass(); // Class InstantiationThis is an instantiation of a class.

  246. $exampleInstance2 = clone $exampleInstance; // “clone” keywordThis keyword creates a shallow copy of the object.

    All references to other variables remain references to those variables.

    Once cloning is complete, the object’s __clone() method is called. Defining this explicitly for the class allows properties to be created or changed.

  247. ExampleClass::class; // Classname ResolutionThis is a keyword that returns a string containing the full classname, including the namespace.

  248. ExampleClass::CLASSCONSTANT; // Class Constant CallThis is a class constant call. It returns the value of the constant in the class definition. It does not require class instantiation.

  249. ExampleClass::$staticProperty; // Static Property CallThis is a static property call. It returns the value of the variable in the class definition. It does not require class instantiation.

  250. $exampleInstance->publicProperty; // Object Property CallThis is a property call on an instantiated object. It returns the value of the property associated with the object.
  251. ExampleClass::staticMethod(); // Static Method CallThis is a static method call. It calls the method in the class definition. It does not require class instantiation.

  252. ExampleClass->staticMethod(); // Alternate Static Method CallThis is a static method call. It calls the method in the class definition. It does not require class instantiation.

  253. $exampleInstance->publicMethod(); // Object Method CallThis is a property call on an instantiated object. It returns the value associated with the object.

  254. try { // “try” BlockThis is a block of code that allows exceptions to be thrown.

    All try blocks must have at least one “catch” statement and/or one “finally” block.

  255. function() { throw new Exception( "hello" ); }; // “throw” StatementThis statement throws a defined exception to a “catch” or “finally” block. This statement, when executed, blocks further code processing in the block.

    There are several predefined exception classes.

    Exceptions can be extended manually.

  256. } catch( Exception $e ) { // “catch” BlockThis block executes when it catches a thrown exception.

    There can be more than one “catch” block for any “try” block.

  257. echo "hello";
  258. } finally { // “finally” BlockThis blocks executes after the “try” and “catch” blocks execute, regardless of the outcome.

  259. echo "hello";
  260. }
  261. ?> // PHP TagThis is the close of the “open” tag, the “open” tag. It tells the server’s PHP engine to stop treating the following instructions as PHP.