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.

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

Listing 15.1     Opening and Closing PHP Tags

This test.php File Returns “Hello World” When Called in the Browser

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.

Data Type

Description

Scalar Types

bool

Boolean value true or false

int

Integer value (integer)

float

Floating point number, also referred to as double

string

Character string

Compound Types

array

A map that assigns values to keys

object

Instance of a class

callable

Callback function

iterable

A pseudo-type that accepts an array or an object that implements the traversable interface

Special Types

resource

A resource is a special variable that is a reference to an external resource. For example, when a file is opened for writing, the connection remains (as a resource) until it is closed.

NULL

Can be used to describe a variable without a value.

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:

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

<?php
var_dump( $_GET );

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:

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.

/ Using the PHP Language

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.

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

Listing 15.1     Opening and Closing PHP Tags

This test.php File Returns “Hello World” When Called in the Browser

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.

Data Type

Description

Scalar Types

bool

Boolean value true or false

int

Integer value (integer)

float

Floating point number, also referred to as double

string

Character string

Compound Types

array

A map that assigns values to keys

object

Instance of a class

callable

Callback function

iterable

A pseudo-type that accepts an array or an object that implements the traversable interface

Special Types

resource

A resource is a special variable that is a reference to an external resource. For example, when a file is opened for writing, the connection remains (as a resource) until it is closed.

NULL

Can be used to describe a variable without a value.

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:

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

<?php
var_dump( $_GET );

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:

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.