Types of php variables. Introduction to PHP Variables


Good day to all. Alexey Gulynin is in touch. In this article I would like to talk about types of variables in php. Like all programming languages, PHP has the concept of a variable. If something is stored somewhere in a program, then it is stored in a variable. Variable declarations in PHP begin with a "$" sign. This may seem strange at first, and many mistakes in the beginning will be due to the fact that you forget to put the "$" sign. Variable names are case sensitive, for example the variable $myvar is not the same as $MyVar . The official documentation says that variable names can consist not only of Latin letters and numbers, but also of any characters whose code is older than 127 (you can even use Russian letters), but I do not advise you to do this, if only because V different encodings Our letters have different codes. In PHP you do not need to explicitly specify the type of a variable, as, for example, in Pascal, PHP interpreter will do everything himself.

Let us briefly describe the main types of variables:

1) Integer, integer;
2) Double, real number, given number should be enough for large number mathematical operations;
3) String, our favorite string;
4) Array, array;
5) Object, object;
6) Resource , some resource that PHP processes in a special way (for example, an open file descriptor);
7) Boolean, logical type, this variable can take 2 values: true or false;
8) NULL, a special type.
All these are the types of variables I will use in following examples and in new articles.

Let's write our first program in PHP:

This program will print "Hello PHP".
If you don’t know how to check the functionality of this script, then I advise you to read the article working with Denwer.
Let's take a closer look at what's going on here. The PHP construct begins with "". We assign the value "PHP" to the $myvar variable. The echo operator will display the following message in the browser "Hello PHP".

Let's sort it out with you how to determine the type of a variable.
There are many various functions to determine the type of a variable:
1) is_integer($var) . Returns true if $var is an integer.
2) is_double($var) . Returns true if $var is a real number.
3) is_string($var) . Returns true if $var is a string.
4) is_bool($var) . Returns true if $var is true.
5) is_numeric($var) . Returns true if $var is either a number or the string representation of a number.
6) is_null($var) . Returns true if $var is null.
7) is_array($var) . Returns true if $var is an array.
8) is_object($var) . Returns true if $var contains a reference to an object.

PHP syntax is borrowed directly from C. Java and Perl also influenced the language's syntax.

Transition from HTML

There are three ways to exit HTML and enter "PHP code mode":

Instruction separation

Instructions (statements) are separated in the same way as in C or Perl - with semicolons.

The closing tag (?>) also implies the end of the statement, so the following entries are equivalent:

Variable types

PHP supports the following types of variables:

  • integer - whole
  • double - number s fractional part
  • string - string variable
  • array - array
  • object - object variable
  • pdfdoc - PDF document (only with PDF support)
  • pdfinfo - PDF info (only if PDF support is available)

The type of a variable is not usually set by the programmer; instead, it is determined by PHP at runtime, depending on the context in which the variable is used.

If you like to specify the type of a variable directly, you can use a statement or function to do this.

Please note that a variable may behave differently in certain situations, depending on what type is defined for it in given time. This is described in more detail in the section.

Initializing a variable

To initialize a variable in PHP, you simply assign a value to it. For most variables this is true; for arrays and object variables, however, a slightly different mechanism may be used.

Initializing Arrays

An array can be initialized in one of two ways: by sequential assignment of values, or by construction (which is described in section).

When you add values ​​to an array sequentially, you simply write the values ​​of the array elements using an empty index. Each subsequent value will be added as the last element of the array.

$names = "Jill"; // $names = "Jill" $names = "Jack"; // $names = "Jack"

As in C and Perl, array elements are numbered starting from 0, not 1.

Initializing objects

To initialize an object variable, use a new prescription to map the given object to the object variable.

Class foo ( function do_foo () ( echo "Doing foo."; ) ) $bar = new foo; $bar -> do_foo();

Variable Area

The scope of a variable is the context within which it is defined. Basically, all PHP variables have one scope. However, within user-defined functions, the local scope of the function is represented. Any variable defined inside a function is by default limited to the function's local scope. For example:

$a = 1; /* global scope */ Function Test () ( echo $a; /* reference to local scope variable */ ) Test ();

This script will not output anything because the echo statement refers to a local version of the variable $a, which is assigned a value outside of that scope. You may notice that there is some difference here from C in that global variables in C automatically take effect inside functions as well, unless they are overwritten by local definitions. This may cause some problems because... Inadvertently, you can change a global variable. In PHP, global variables must be declared globally within a function if they are to be used within that function. For example:

$a = 1; $b = 2; Function Sum () ( global $a, $b; $b = $a + $b; ) Sum (); echo $b;

The above script will return the value "3". Since $a and $b are declared globally within the function, references to these variables are treated as references to their global versions. There is no limit to the number of global variables that can be manipulated within a function.

The second way to access variables from the global scope is to use a special defined PHP array$GLOBALS. In this case, the previous example can be written as:

$a = 1; $b = 2; Function Sum () ( $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; ) Sum (); echo $b;

The $GLOBALS array is an associative array in which the name of the global variable is the key and the value of that variable is the value of the array element.

Another important characteristic from the domain of the variable is static variable. A static variable exists only in the local area of ​​a function, but it does not lose its value when the program leaves that area during execution. Consider the following example:

Function Test () ( $a = 0; echo $a; $a++; )

This function is completely useless in practice because every time it is called it sets $a to 0 and prints "0". The $a++ expression, which increments the value of a variable, is also useless because the variable $a disappears when the function exits. To enable a counting function that does not lose track of the current account, the $a variable is declared as static:

Function Test () ( static $a = 0; echo $a; $a++; )

Now, every time the Test() function is called, it will print the value of $a and increment it.

Static variables are also very important when functions are called recursively. Recursive functions are those that call themselves. You need to be careful when composing a recursive function, because spelled incorrectly can make recursion undefined. You must be sure that the method used to terminate the recursion is appropriate. Next simple function Recursively counts to 10:

Function Test () ( static $count = 0; $count++; echo $count; if ($count< 10) { Test (); } $count--; }

Mutable Variables

Sometimes it is convenient to give variables mutable names. Such names can change dynamically. A normal variable is set like this:

A mutable variable takes a value and treats it as a variable name. In the above example the value hello can be used as a variable name by using two consecutive dollar signs, i.e.:

From this point of view, two variables are defined and stored in the PHP symbol tree: $a with the content "hello" and $hello with the content "world". So, instructions:

Echo "$a $($a)";

does the same thing as the instruction:

Echo "$a $hello";

namely, they both output: hello world.

To use mutable variables with arrays, the ambiguity problem needs to be resolved. This means that if you write $$a then parser you need to know whether you mean to use $a as a variable, or whether you mean to use $$a as a variable and as an index of that variable. The syntax for resolving such ambiguity is: $($a) for the first case and $($a) for the second.

Variables outside of PHP

HTML Forms (GET and POST)

When the form handler is a PHP script, the form's variables are automatically available to that PHP script. For example, consider the following form:

Example 5-2. Simple Form Variable

Name:

When activated PHP forms will create a $name variable whose value will be the content that was entered into the field Name: of this form.

PHP also understands arrays in the context of shape variables, but only one-dimensional ones. You can, for example, group related variables together, or use this property to determine the values ​​of variables when multiple selecting an input:

If the PHP track_vars attribute is enabled, via configuration setting or directive, then variables activated via POST or GET methods will also be in global associative arrays$HTTP_POST_VARS and $HTTP_GET_VARS respectively.

ACTIVATION FIGURE variable names

When activating (launching) a form, you can use a picture (image) instead of a standard launch button, in a tag like this:

When the user clicks anywhere above such a graphic, the accompanying form is submitted to the server with two additional variables, sub_x and sub_y. They contain the coordinates of the location where the user clicked the mouse button within a given picture. It may be noted that in practice, the actual variable names passed by the browser contain a dot instead of an underscore, but PHP converts the dot to an underscore element automatically.

HTTP Cookies

PHP obviously supports HTTP cookies as defined in . Cookies are a mechanism for storing data in a remote browser, used to support the exchange procedure or identify the user's response. Cookies can be set using the function . Cookies are part of the HTTP header, so the function must be called before any transfer data is sent to the browser. This is the same limitation as for the function . Any cookies sent to you by the client are automatically converted to PHP variables, just like data GET methods and POST.

If you need to assign multiple values ​​to a single cookie, simply add square brackets to the cookie name. For example:

SetCookie("MyCookie", "Testing", time()+3600);

Please note that the current cookie will replace the previous one with the same name in your browser, unless the path or domain is different. Therefore, when working with card service programs, you can use a counter to save data and send its values ​​further, etc.

Example 5-4. SetCookie function example

$Count++; SetCookie("Count", $Count, time()+3600); SetCookie("Cart[$Count]", $item, time()+3600);

Environment Variables

PHP automatically creates environment variables just like regular variables.

Echo $HOME; /* Shows the HOME environment variable if it is set. */

Although the GET, POST, and Cookie mechanisms also automatically create PHP variables when information arrives, sometimes it is better to explicitly read the environment variable to ensure that it is retrieved correct version. The function can be used for this . To set the value of an environment variable, use the function .

Server configuration directives

Change type

PHP does not require an explicit type definition when declaring a variable; the type of a variable is determined by the context in which it is used. That is, if you assign a string value to a variable var , var becomes a string. If you then assign to a variable var the value of an integer (number), then it will become an integer.

An example of automatic type conversion in PHP is the addition operator "+". If any of the operands is a number with a fractional part (type double), then all operands evaluate to double and the result will be of type double. Otherwise, these operands will be interpreted as integers and the result will also be of type integer. Note that this does NOT change the types of the operands themselves, only the evaluation of these operands changes.

$foo = "0"; // $foo is a string (ASCII 48) $foo++; // $foo is the string "1" (ASCII 49) $foo += 1; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a double (3.3) $foo = 5 + "10 Little Piggies"; // $foo is an integer (15) $foo = 5 + "10 Small Pigs"; // $foo is an integer (15)

If you want a variable to be forced to be evaluated as having a specific type, see the section. If you wish to change the type of a variable, see

Last update: 11/1/2015

PHP is a language with dynamic typing. This means that the data type of a variable is inferred at runtime, and unlike some other programming languages, PHP does not need to be specified before variable type data.

PHP supports eight simple type data:

    boolean (boolean type)

    integer (whole numbers)

    double (fractional numbers)

    string

    array

    object

    resource

Integer (integer type)

Represents a 32-bit signed integer (-2,147,483,648 to 2,147,483,647).

$int = -100; echo $int;

Here, the $int variable represents an integer type because it is assigned an integer value.

Except decimal integers PHP numbers has the ability to also use binary, octal and hexadecimal numbers. Number patterns for other systems:

    hexadecimal: 0

    octal: 0

    binary: 0b

For example:

"; echo "int_2 = $int_2
"; echo "int_8 = $int_8
"; echo "int_16 = $int_16"; ?>

Type double (floating point numbers)

The size of a floating point number varies by platform. The maximum possible value is typically ~1.8e308 with a precision of about 14 decimal digits. For example:

Type boolean (boolean type)

Boolean type variables can take two values: true and false, or in other words, true and false. Most often, Boolean values ​​are used in conditional constructs:

"; if($foo) echo $a+$b; else echo $a-$b; $foo = false; echo "
foo = false
"; if($foo) echo $a+$b; else echo $a-$b; ?>

The if() statement tests the truth of an expression. IN in this case The value of the $foo variable is checked. Either it is true or equal to true, then the expression following the if statement is executed. And if the variable or expression in the if statement is false , then the expression after else statement.

Special value NULL

A NULL value indicates that the variable's value is undefined. Usage given value useful in cases where we want to indicate that a variable has no value. For example, if we simply define a variable without initializing it, and then try to use it, the interpreter will give us a diagnostic message that the variable is not set:

Using NULL will help avoid this situation. In addition, we will be able to check for the presence of a value and, depending on the results of the check, perform certain actions:

The NULL constant is not case sensitive, so we can write it like this:

$a=null;

Type string

You can use strings to work with text. There are two types of strings: double quotes and single. The type of quotes determines how strings are processed by the interpreter. Thus, variables in double quotes are replaced by values, but variables in single quotes remain unchanged.

"; echo $result; $result = "$a+$b"; echo $result; ?>

In this case we will get the following output:

10+5$a+$b

In addition to regular characters, a line may contain Special symbols, which may be misinterpreted. For example, we need to add a quote to the string:

$text = "Apple II model";

This entry will be incorrect. To fix the error, we can combine different types of quotes ("Apple II Model" or "Apple III Model") or use a slash to insert a quote into the string:

$text = "Model \"Apple II\"";

Type resource

A resource represents a special variable that contains a reference to an external resource. For example, files or database connections can be used as an external resource. Resources are created and used by special functions. Next, we'll take a closer look at working with files and connecting to a database.

array type (associative arrays)

An associative array defines a set of elements, each of which represents a key=>value pair. Let's create an array of 4 elements:

An array is created using the array() construct, which defines the elements. Next we output the second element of the array. Since the counting of elements in the array starts from zero, to access the second element we need to use the expression $phones

Since there are only four elements in the array, we cannot use a number greater than 3 as the key, for example $phones.

It is known that PHP is a weakly typed programming language. What does this mean? We can perform various operations between variables different types, and get “something” as an output. On the one hand, it's convenient. A string turns into an integer, an integer can become an object, and the object can smoothly transition into an array.

But any programmer when creating websites on php language sooner or later you come across the fact that in many cases the types of variables should be specified (or at least checked before use).

This strict attitude towards variables is due to the fact that most PHP scripts are susceptible to the unhealthy attention of attackers in order to substitute parameters various types in the site's query string. This can lead to the generation of an error with the disclosure of the path where the file is located, up to bypassing some restrictions.

Elevating user rights in earlier versions WordPress by passing the username as an array, not a string, to the authentication script in the admin panel, or by substituting in the query string instead of integers (for example, news id) - specially crafted sql queries for the purpose of unauthorized access, creating so-called sql on the site injections.

So, whenever possible, check the types of variables before using them, or explicitly cast them while programming in PHP. Here are the functions that will be useful to us to control the security of input data:

  • (string) trim($str)Accepted parameters:$var is a string to remove whitespace and line breaks. Trims end-of-line characters and whitespace characters at the beginning and at the end of the line, returns a variable of string type.
  • (bool) is_string($var)Accepted parameters:$var – variable to check. Is $var a string? Returns: true: if it is, false: if it is not.
  • (bool) is_numeric($var)Accepted parameters:$var – variable to check. Is $var a set of numbers? Returns: true: if it is, false: if it is not.
  • (bool) is_float($var)Accepted parameters:$var – variable to check. Is the variable $var real number? Returns: true: if it is, false: if it is not.
  • (bool) is_array($var)Accepted parameters:$var – variable to check. Is $var an array? Returns: true: if it is, false: if it is not.
  • (bool) is_int($var)Accepted parameters:$var – variable to check. Is $var an integer? Returns: true: if it is, false: if it is not.
  • (bool) isset($var)Accepted parameters:$var – variable to check. Checks whether the variable $var (any data type) exists; if it exists, returns true, otherwise returns false.
  • (bool) is_resource($var)Accepted parameters:$var – variable to check. Is $var a resource? Returns: true: if it is, false: if it is not.
  • (bool) empty($var)Accepted parameters:$var – variable to check. Checks whether an existing variable is empty or not, return values: true for values ​​("", 0, 0.0, "0", NULL,FALSE,array()), false otherwise.

Example of use when programming in PHP scripts. We pass the $user data array received during user registration to the form via a post request:

Another example of use in PHP scripts. Let's ask a question to the database:

The point is that it is very useful to check whether a parameter is a resource before passing a function that obviously requires a parameter of type resource. For example, in case sql queries this approach may indicate an error that occurred in the request, or simply that the database server (or the current connection) is busy.

When working with data values ​​in PHP, we need convenient way storage so that we can easily access them and refer to them if necessary.

PHP global variables can be thought of as a location in a computer's memory where data should be stored. When a variable is declared, it is given a name that can be used to refer to it in other places program code. The value of a variable can be accessed and changed, and the type of a variable can be changed by referring to its name.

Naming and creating a variable in PHP

All PHP variable names must be prefixed with $. It informs the language preprocessor that it is dealing with a variable. The first character of the name must be a letter or an underscore (_) character. Other characters can only be letters, numbers, or underscores. All other characters are considered invalid for use in a variable name.

Let's look at some valid and invalid PHP variable names:

$_myName // valid. $myName // valid. $__myvar // acceptable. $myVar21 // acceptable. $_1Big // not allowed, underscore must follow the letter. $1Big // not valid - must start with a letter or underscore. $_er-t // invalid - contains an alphanumeric character (-).

PHP variable names are case sensitive. This means that PHP considers the variable $_myVariable to be different from the variable » $_myvariable.

Assigning a value to a PHP variable

Variables are initialized with values ​​using the PHP assignment operator (=). To assign a value to a variable, its name is placed to the left of the expression, followed by an assignment operator. The value that is assigned after PHP variable declarations is placed to the right of the assignment operator. Line, as in all PHP expressions code, ends with a semicolon (;).

Let's start by assigning the word "Circle" to a variable called myShape:

$myShape = "Circle";

We declared a variable called myShape and assigned it the string value "Circle". In a similar way, you can declare a variable containing a numeric value:

$numberOfShapes = 6;

We create a variable numberOfShapes and assign it numeric value 6. Once a PHP variable has been created, its assigned value can be changed using the assignment operator:

Accessing PHP Variable Values

Now we must consider how to access the current value assigned to a variable. For example, if we want to display the value we assigned to the numberOfShapes variable, we need to reference it in the echo command:

This will produce the following output in the browser:

Figure number 6.

You can display the value of the myShape variable in the same way:

The examples used to demonstrate accessing variable values ​​are simple because we always had a space after the variable name. The question arises, What to do if you need to put other characters immediately after the PHP variable name. For example:

What we need in this case is output as follows:

The circle is the 6th figure.

Unfortunately, PHP will see the th at the end of the $numberOfShapes variable name as part of the name. It will then try to output the value of the $numberOfShapesth variable, which does not exist. This causes the value of this variable to not be displayed:

A circle is a figure.

You can get around this problem by setting braces(( )) around the variable name to escape it from other characters:

Which gives us the desired result:

The circle is the 6th figure.

Changing the type of a PHP variable

PHP variable types: integer, real, boolean, array, object and string. First, let's look at changing the type of a variable after it has been created.

PHP is a weakly typed language. The rules of a strongly typed language dictate that once a variable has been declared as a specific type, its type cannot be changed later. In Java, for example, you cannot assign a floating-point number to a variable that was originally declared as a string.

Weakly typed languages ​​such as PHP and JavaScript allow the type of a variable to be changed at any point in its existence variable by assigning it a value of a different type. For example, you can create a variable, assign it an integer value, and later change it to string :

The process of dynamically changing the type of a variable is called automatic type conversion.

Checking if a variable is set

In PHP, checking for the existence of a variable is a commonly used operation. This language provides a mechanism to provide this capability by using the isset() function. To check if it has variable value, call the isset() function, which is passed the variable name as an argument:

Translation of the article “ An Introduction to PHP Variables” was prepared by the friendly project team.

Good bad







2024 gtavrl.ru.