15.3 Variables, Data Types, and Operators
Once MAMP has been set up, you’re ready to go. However, before we turn to a concrete example, I first want to discuss the basic programming structure. For this purpose, you’ll need to create a file called test.php and open it in an editor of your choice. This file will be placed in the folder you specified earlier. As shown in Figure 15.1, for me, this folder is the Sites/localhost directory, which is located in my user folder. Within the test file, you can specify any HTML code you like.
You can then define PHP areas within the opening <?php and closing ?> tags, as shown in Listing 15.1. echo outputs “Hello World.” Figure 15.3 shows how the http://localhost:8888/test.php address was called in the browser. As expected, PHP returns the corresponding string.
Opening and Closing PHP Tags
Note that the closing PHP tags at the end of a file can be omitted. As a matter of fact, omission is even recommended (https://www.php.net/manual/de/language.basic-syntax.phptags.php). Skipping the closing tag ensures that no spaces or blank lines are accidentally sent to the browser afterwards. Otherwise, an unwanted output would be created that was not intended by the programmer. Even worse, functions that depend on HTTP headers often fail, for example, sessions, cookies, or redirects.
Listing 15.1 Opening and Closing PHP Tags
Figure 15.3 This test.php File Returns “Hello World” When Called in the Browser
15.3.1 Using Variables
Listing 15.2 shows how a variable is usually declared and initialized, always starting with a dollar sign ($), followed by a name (which may consist of uppercase and lowercase letters), and an underscore (_). Numbers may also appear, but not at the beginning, or more precisely not directly after the dollar sign. In addition, PHP has some naming guidelines that you should follow (https://www.php.net/manual/en/userlandnaming.php). A standalone declaration like in JavaScript (see Chapter 4, Section 4.2.1) does not exist in PHP. Likewise, the casting, represented in our example by the preceding (string), can usually be omitted since PHP automatically recognizes or defines the type of the variable. (More on this topic shortly.)
<?php
$firstName = 'John'; // Variable declaration and initialization
$firstName = (string) 'John'; // Type casting
Listing 15.2 Declaring Variables
PHP offers several primitive data types, listed in Table 15.2.
Table 15.2 The Ten Primitive Data Types of PHP
Juggling with Types (Type Juggling)
As mentioned earlier, PHP does not require or support an explicit type definition in the variable declaration. The type of a variable is instead determined by the concrete value that the variable contains. In other words, if a string value is assigned to the $var variable, $var becomes a string. If $var is subsequently assigned an int value, it becomes an integer. Listing 15.3 shows how PHP proceeds.
<?php
$var = '1'; // $var is a string.
$var = $var * 1; // $var is now an integer.
$var = (string) $var; // $var is a string again.
Listing 15.3 Type Juggling in PHP
To force a variable to evaluate as a specific type, you can cast it or use the settype() function (https://www.php.net/manual/en/function.settype.php). Casting (in the last line of our example) converts the value to a specific type by writing the type in parentheses before the value to be converted. The following values are allowed:
-
(int) or (integer)
-
(bool) or (boolean)
-
(float) or (double) (in PHP 7 and earlier, (real) is also possible)
-
(string) or (binary)
-
(array)
-
(object)
-
(unset) (value allowed only in PHP 7 and earlier)
We recommend using only the values named first, for example, (int) instead of (integer) because the second values are only aliases. These aliases could possibly disappear in later PHP versions, just as (real) is no longer possible in PHP 8.
References
A variable does not always have to be assigned a value. Instead, you can also pass it a reference by using the & operator , as shown in Listing 15.4. A reference is therefore a pointer to another variable. If a reference is changed, the value of the referenced variable changes as well.
<?php
$lastName = 'Doe';
$birthName = &$lastName; // now also contains the value 'Doe'.
$birthName = 'samplewife'; // $birthName is changed. Thereby
// also $lastName.
echo $lastName; // Output of $lastName: 'Deer'.
Listing 15.4 Assigning a Reference
Predefined Variables
In PHP, some variables are made available depending on the current namespace (see box). For a complete list, you should visit https://www.php.net/manual/en/reserved. variables.php. As an example, the $_GET variable contains all parameters given to the script via the Uniform Resource Locator (URL) http://localhost:8888/test.php?firstName=John&lastName=Doe. Listing 15.5 shows the output of the variables from the script shown in Listing 15.6.
array (size=2)
'firstName' => string 'John' (length=4)
'lastName' => string 'Doe' (length=3)
Listing 15.5 $_GET Variable Now Containing the Two Values Passed by the URL
Listing 15.6 var_dump() Providing a Nice Output in the Browser
Namespace
When you define variables, functions, or classes, they are placed in the global namespace. Thus, for example, you can access a constant even if the constant is defined in a completely different file. Of course, this file must be included using one of the keywords include, require, include_once, or require_once (see https://www.php.net/manual/en/language.control-structures.php), as shown in the following examples.
<?php
const FOO = "Hello World";
Listing 15.7 hello-world.php file
<?php
include "hello-world.php";
echo FOO;
Listing 15.8 test.php File
When test.php is called, the browser will output “Hello World.”
However, you can also define your own namespaces by using the namespace keyword, as shown in Listing 15.9. The FOO constant is now no longer in the global namespace but instead in the hello_world namespace.
<?php
namespace hello_world;
const FOO = "Hello World";
Listing 15.9 hello-world.php File with Namespace
The constant can now be accessed only via an additional specification of the namespace.
<?php
include "hello-world.php";
echo \hello_world\FOO;
Listing 15.10 test.php File with Access to the FOO Constant of a Different Namespace
Note that the namespace must be enclosed in backslashes (\) when referenced.
Scope and Variable Variables
Variables are only valid in certain areas, as is the case in nearly every programming language. You’ll learn more about functions in Section 15.5, but note that variables defined in functions do not exist outside their functions. Some exceptions exist, however, and the global keyword enables you to bypass this restriction. In most cases, however, global variables should be avoided, so I won’t describe them in greater detail. To learn more about this topic, as well as for an explanation of the static keyword, check out https://www.php.net/manual/en/language.variables.scope.php.
Variable variables are somewhat more complex. To use this type of dynamic variable, detailed instructions are available at https://www.php.net/manual/en/language.variables.variable.php.
15.3.2 Using Constants
Constants are variables that cannot be changed. Constants are defined by the define() function, as shown in Listing 15.11, where you can also see how the call is made, namely, without a preceding dollar sign.
Constants can also be written in lowercase, but the general convention is to use uppercase letters. Constants are always global, which means they can be accessed from anywhere, from a function as well as from a class method.
<?php
define( 'MINUTE_IN_SECONDS', 60 );
define( 'HOUR_IN_SECONDS', 60 * MINUTE_IN_SECONDS );
define( 'DAY_IN_SECONDS', 24 * HOUR_IN_SECONDS );
Listing 15.11 Defining Constants
Predefined and Magic Constants
PHP uses some predefined constants/magic constants. Predefined constants start with a double underscore: __FILE__, for example, returns the full path and file name of the file that’s currently being executed. You should avoid declaring constants in your projects that start with a double underscore or with PHP_, as PHP itself may one day introduce a constant with the same name. For a complete current list, refer to https://www.php.net/manual/en/language.constants.magic.php and https://www.php.net/manual/en/reserved.constants.php.
15.3.3 Using Operators
As in all other programming languages, many operators are available in PHP that allow you to compare or modify variables, such as the following:
-
Arithmetic operators are used for calculations. The following are available: + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). In addition, these operators include the increment and decrement operators (++ and --), which add or subtract 1 from a number. A power of a number can be calculated by using **.
-
The assignment operator is the equal sign (=). You’ve already encountered this operator whenever we’ve set values for variables. In addition, combined operators allow you to use the value of a variable in an expression and then assign the result of that expression as a new value (shown later in Listing 15.17). These operators include += (for addition), -= (for subtraction, *= (for multiplication), /= (for division), %= (for modulus calculation), **= (for exponentiation), and .= (the string operator for concatenation).
-
Bit operators allow you to check and manipulate specific bits in an integer. The following bit operators are available: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (bitwise shift to the left), and >> (bitwise shift to the right).
-
Comparison operators allow you to compare values directly. The following operators are available: == (equal to), === (identical to), != or <> (not equal to), !== = (not identical to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), and <=> (spaceship, see box). “Identical to” in PHP means not only is the value identical but also its type. Refer to Listing 15.12 for more information on this topic.
<?php
$a = '1';
$b = 1;
$c = $a == $b; // Returns true.
$d = $a === $b; // Returns false because the type comparison fails.Listing 15.12 Comparisons of Equality and Identity
-
Operator for program execution: Backticks (``) can be used to execute external programs. Note that backticks are not simple execution characters and that execution will fail if the shell_exec() function has been disabled. The line $file_list = `ls -al`; tries to execute the ls command line tool, which lists all files and directories of the current folder.
-
Logical operators are for using Boolean values. The following operators can be used: and or && (logical AND), or or || (logical OR), xor (exclusive OR), and ! (negation).
-
Array operators are used to compare or manipulate arrays. $a + $b unites two arrays. == returns true if both arrays contain the same key-value pairs. === returns true if both arrays contain the same key-value pairs in the same order and they are of the same type. Accordingly, != or <> mean that two arrays are not equal. !== in turn means “not identical,” where a type comparison is also performed.
-
Type operator: The instanceof keyword checks if an object belongs to a certain class.
-
The ternary operator (shown in Listing 15.13) is another comparison operator that returns an expression and replaces a longer if statement. This operator also available in the short version, where the middle part can be omitted, as shown in Listing 15.14.
<?php
$action = ( empty( $_POST['action'] ) ) ? 'standard' : $_POST['action'];
// The above is identical to the IF statement below.
if (empty($_POST['action'])) {
$action = 'standard';
} else {
$action = $_POST['action'];
}Listing 15.13 Ternary Operator
<?php
$firstName = '';
$firstName = $firstName ?: 'John'; // Contains 'John'.
$firstName = 'Anne';
$firstName = $firstName ?: 'John'; // Contains 'Anne'.Listing 15.14 Short Ternary Operator
-
Quite similar to the ternary operator is the null coalescing operator. This operator is also an assignment operator in combination with NULL, as shown in Listing 15.15. In particular, the result of the left side does not give any hint or warning if the value does not exist.
<?php
$firstName = $firstName ?? 'John'; // Returns 'John'
$firstName = 'Anne';
$firstName = $firstName ?? 'John'; // Returns 'Anne'Listing 15.15 Null Coalescing Operator
The Spaceship Comparison Operator
Since PHP 7, we’ve had the spaceship operator, which is represented by the characters <=>. Also known as the three-way operator, this operator performs a less-than-equal, a greater-than-equal, and an is-equal-to comparison.
Listing 15.16 The Spaceship Operator in Action
In our example, -1 is the output because $a is less than $b. If $a were greater than $b, (the positive number) 1 would be the output. If both values were equal, 0 would be the output.
<?php
$a = 3;
$a += 5; // $a now has the numerical value 8
$name = 'John';
$name .= ' Doe'; // $name now contains 'John Doe'.
Listing 15.17 Combined Operators in Action
Note
A good overview of all operators available in PHP, with many examples, is available at https://www.php.net/manual/en/language.operators.php.
