Environment variables (environment) in Windows contain various information about system settings and the user's environment. A distinction is made between user, system, and process environment variables.

The easiest way to view content environment variables in Windows - open system properties ( sysdm.cpl) -> Advanced -> Environment Variables. As you can see, there are two sections in the opened section: the upper one contains the user's environment variables, the lower one contains the system ones.

In addition, environment variables are stored in the system registry. User variables are stored in the . Systemic - in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

You can display the values ​​of all environment variables in command line Windows. The command is simple:

The command will list the environment variables and their values.

In PowerShell, to display all environment variables, you can use the command:

If you want to display the value of only one variable, you need to use the echo command, and the variable name must be enclosed in percent signs. For example,

echo %systemroot%

set > c:\tmp\env_var.txt

The environment variables of a particular process can be obtained using the free Process Explorer utilities(from Sysinternals). Just open the process properties and go to the tab Environment.

variables in php is a kind of information container that can contain different types data (text, numbers, arrays, and so on). In general, variables allow you to create, store, modify, and then quickly access the information specified in them.

How to create a variable in PHP

Initially, the variables contain the sign $ (dollar) - designation of the use of a variable, then letters Latin alphabet(from a to z and small and large), at the end I can contain numbers. It is also allowed to use an underscore (not at the end) in the title.

How to name variables:

$var
$variable
$year1945
$_variable
How not to name variables:

$1 - consists of only a digit
$1var - you can't start a variable name with a number
$/var - only underscore is allowed from additional characters _
$variable - Cyrillic is allowed php documentation but not recommended
$var iable - spaces cannot be used

Each variable is assigned a value. The sign is used to assign a value. = (equals). During script processing, the value of a variable can change repeatedly depending on various conditions.

$city = "Moscow"; // the variable $city was assigned the string (in quotes) value Moscow
$year = 1147; // and the $year variable was assigned the numeric value 1147
?>

$name = "Alexander";
$Name = "Alex";
echo "$name, $Name"; // prints "Alexander, Alexey"
?>

PHP variable output

Separately, you should analyze how to display variables using output statements, whose work we analyzed in the last lesson Creating a PHP page. output operators. . Below is a series good examples with comments.

// This is how we set the values ​​of the variables
$name1 = "Alex";
$name2 = "Alexander";

// Display variables
echo $name2; // Output: Alexander
echo "name1 is $name1"; // name1 is Alexey

// When using single quotes, output
// variable name, not value
echo "name1 is $name1"; // output: name1 is $name1

// you can display just the values ​​of variables
echo $name1; // Alexei
echo $name1,$name2; // AlexeyAlexander
echo $name1." ".$name2; // Alexey Alexander
echo "$name1, $name2"; // Alexey, Alexander

echo<<This uses the "here document" syntax to output
multiple lines with $variable substitution.
END;

PHP Variable Operations

Arithmetic operations in PHP
In the case of numerical values, arithmetic operations can be performed: addition, subtraction, multiplication, and so on.

-$a(negation) Change the sign of $a.
$a + $b(addition) The sum of $a and $b.
$a - $b(subtraction) The difference between $a and $b.
$a * $b(multiply) The product of $a and $b.
$a / $b(division) The quotient of $a divided by $b.
$a % $b(modulo) The integer remainder of $a divided by $b.
Consider examples

$a = 2; // note that in the case of numbers, quotes are not put
$b = 3; // note that in the case of numbers, quotes are not put

$result = $a + $b; // add variables
echo $result; // prints 5

$result = $b - $a; // add variables
echo $result; // prints 1

Increment and decrement operations in PHP
These operations will be useful mainly in the construction of cycles, which we will talk about a little later.
prefix- operators written BEFORE the variable ( --$a; ++$a). Return the value of the variable before changes.
Postfix- operators written after the variable ( $a--; $a--). Return the value of a variable with changes.
Increment- increasing the value.
Decrement- decreasing value.

++$a prefix increment. Increments $a by one and returns the value of $a.
$a++ postfix increment. Returns the value of $a and then increments $a by one.
--$a prefix decrement. Decrements $a by one and returns the value of $a.
$a-- Postfix decrement. Returns the value of $a and then decrements $a by one.
echo "

Postfix increment

";
$a = 5;
echo "Should be 5: " . $a++ . "\n";

echo"

prefix increment

";
$a = 5;
echo "Should be 6: " . ++$a . "\n";
echo "Should be 6: " . $a . "\n";

echo"

Postfix decrement

";
$a = 5;
echo "Should be 5: " . $a-- . "\n";

echo"

prefix decrement

";
$a = 5;
echo "Should be 4: " . --$a . "\n";
echo "Should be 4: " . $a . "\n";
?>

Assignment operations in PHP
Base operator looks like = . At first glance, it might seem that this is the equals operator. Actually it is not. In effect, the assignment operator means that the left operand gets the value of the right expression, (i.e., is set to the resulting value). Combined Operators- these are operators that allow you to use the previous values ​​of variables for subsequent operations (append to a string variable (with text) or add numeric values).

$a = ($b = 2) + 4; // result: $a is set to 6, $b is set to 2.

$a = 2;
$a += 3; // sets $a to 5, similar to $a = $a + 3;
$b = "Hi";
$b .= "Peace!"; // sets $b to "Hello World!" like $b = $b . "There!";

There are also comparison operations and brain teaser, but we will talk about them in the next lessons. I will try not to scare you with a large amount of information at once!)

In this lesson, the scope is covered. PHP variables. Explains the difference between local and global scope, shows how to access global variables inside a function, how to work with superglobals and create static variables.

When you start learning PHP and you start working with functions and objects, the scope of variables causes some confusion. Fortunately PHP's rules in this regard are very easy to understand (compared to other programming languages).

What is scope?

Variable scope is the context within which a variable was defined and where it can be accessed. PHP has two variable scopes:

  • Global- variables can be accessed anywhere in the script
  • Local- variables can only be accessed within the function in which they were defined

Variable scope, and especially local scope, greatly simplifies code management. If all variables were global, then they could be changed anywhere in the script. This would lead to chaos and large scripts, since very often different parts of the script use variables with the same name. By limiting the scope to the local context, you define the boundaries of the code that can access the variable, making the code more robust, modular, and easier to debug.

Variables with global scope are called global variables, and those with local scope are called local variables.

Here is an example of how global and local variables work.

"; ) sayHello(); echo "Value \$globalName: "$globalName"
"; echo "Value \$localName: "$localName"
"; ?>

Hi Harry! $globalName value: "Zoya" $localName value: ""

In this script, we have created two variables:

  • $globalName- this is global variable
  • $localName- this is local a variable that is created inside the sayHello() function.

After the variable and function are created, the script calls sayHello() , which prints "Hi Harry!" . The script then tries to output the values ​​of the two variables using the echo function. Here's what happens:

  • Because $globalName was created outside of the function, it is available anywhere in the script, so "Zoya" is displayed.
  • $localName will only be available inside the sayHello() function. Because the echo expression is outside the function, PHP does not allow access to the local variable. Instead, PHP assumes that the code will create a new variable named $localName , which will default to an empty string. that's why the second call to echo outputs the value "" for the $localName variable.

Accessing global variables inside a function

To access a global variable outside the function just write her name. But to access a global variable inside a function, you must first declare the variable as global in the function using the global keyword:

Function myFunction() ( global $globalVariable; // Accessing the global variable $globalVariable )

If you don't, then PHP assumes that you are creating or using a local variable.

Here is an example script that uses a global variable inside a function:

"; global $globalName; echo "Hello $globalName!
"; ) sayHello(); ?>

When executed, the script will output:

Hi Harry! Hello Zoya!

The sayHello() function uses keyword global to declare the $globalName variable as global. She can then access the variable and output its value ("Zoya").

What are superglobals?

PHP has a special set of predefined global arrays that contain various information. Such arrays are called superglobals, since they are accessible from anywhere in the script, including inner space functions and do not need to be defined using the global keyword.

Here is a list of superglobals available in PHP version 5.3:

  • $GLOBALS - list of all global variables in the script (excluding superglobals)
  • $_GET - contains a list of all form fields submitted by the browser with a GET request
  • $_POST - contains a list of all form fields submitted by the browser using a POST request
  • $_COOKIE - contains a list of all cookies sent by the browser
  • $_REQUEST - contains all key/value combinations contained in $_GET, $_POST, $_COOKIE arrays
  • $_FILES - contains a list of all files downloaded by the browser
  • $_SESSION - allows you to store and use session variables for the current browser
  • $_SERVER - contains information about the server, such as the file name of the script being executed and the IP address of the browser.
  • $_ENV - Contains a list of environment variables passed to PHP, such as CGI variables.
For example, you can use $_GET to get the values ​​of the variables contained in the script's request URL string, and display them on the page:

If you run the above script with the URL http://www.example.com/script.php?yourName=Fred, it will output:

Hey Fred!

Warning! In a real script, this data transfer should never be used due to weak security. You should always check or filter the data.

The $GLOBALS superglobal is very convenient to use, as it allows you to organize access to global variables in a function without the need to use the global keyword. For example:

"; ) sayHello(); // Displays "Hello Zoya!" ?>

Static variables: they are somewhere around

When you create a local variable within a function, it only exists while the function is running. When the function terminates, the local variable disappears. When the function is called again, a new local variable is created.

In most cases, this works great. Thus, the functions are self-sufficient and always work the same way every time they are called.

However, there are situations where it would be convenient to create a local variable that "remembers" its value between function calls. Such a variable is called static.

To create a static variable in a function, you must use the static keyword before the variable name and be sure to give it an initial value. For example:

Function myFunction() ( static $myVariable = 0; )

Consider a situation where it is convenient to use a static variable. Let's say you create a function that, when called, creates a widget and prints out the number of widgets already created. You can try writing code like this using a local variable:


"; echo createWidget() . " we have already created.
"; echo createWidget() . " we have already created.>
"; ?>

But, since the $numWidgets variable is created every time the function is called, we get the following result:

We create some widgets... 1 we have already created. 1 we have already created. 1 we have already created.

But by using a static variable, we can keep the value from one function call to the next:

"; echo createWidget() . " we have already created.
"; echo createWidget() . " we have already created.
"; echo createWidget() . " >we have already created.
"; ?>

Now the script will produce the expected result:

We create some widgets... 1 we have already created. 2 we have already created. 3 we have already created.

Although a static variable retains its value between function calls, it is only valid while the script is running. As soon as the script completes its execution, all static variables are destroyed, as well as local and global variables.

That's all! Refer often to the PHP documentation.

Surely you have a closet or chest of drawers at home. The principle of their use is simple: we put things there that we do not need right now, but may be needed after a while.

Variables are arranged in exactly the same way. You can put some value in them and store it there until you need it.

Creating Variables

You can put a value in a variable like this:

In the code above, we created the $name variable and put the value Ivan into it, then we created the $age variable and assigned the value 20 to it.

The name "variable" means that its value can change during script execution:

In some languages, a variable must first be "declared" before being used. There is no declaration in PHP - a variable is created the moment you put a value into it.
However, PHP programmers often say "declare a variable" instead of "create a variable".

Also, instead of "put a value in a variable" it is often said to "assign a value".
The reason is simple - the symbol = , thanks to which we store the value in a variable, is called the "assignment operator". Hence the term "assign".

Variable naming conventions

1. The variable name begins with the $ symbol.

2. The second character can be a letter or an underscore _

Variable names are case sensitive. $name and $Name are different variables.

Displaying the value of a variable on the screen

You can display a variable using the echo command already known to us:

The echo command allows you to display multiple values ​​at once:

Note that we passed 2 values ​​to echo, separating them with a comma. So we can pass as many values ​​as we want. The following two examples will produce the same result:

Also in PHP there is a shorthand syntax for outputting variables. Instead of

Prior to PHP 5.4, the shorthand syntax only worked if the short_open_tag directive was enabled in the PHP settings, which also allows the use of a shortened opening tag

Checking the value of a variable

The echo command is not always convenient for checking the current value of a variable. For example, if you try to display an empty string "" absolutely nothing will be displayed on the screen. And it is not clear what the reason is - in an empty variable or non-working code.

Therefore, the var_dump() function is used to check the value of a variable:

Result of script execution:

String(5) "Vasya" string(0) ""

As you can see, PHP outputs not only the contents of the variable, but also the number of characters, and even the type of the variable (string). We will look at data types in detail in the next lessons.

Removing variables

You can remove an existing variable using the unset() function:

And now it's time to practice a little.

Remember, almost any PHP problem can have multiple solutions. Therefore, if your decisions differ from those written on this site, this does not mean at all that you have done something wrong.

Write a script that:
1. Creates variables named title and content and some values.
2. Displays the value of the title variable inside the h1 tag, and the value of the content variable inside the div tag.

Show Solution

", $title, ""; echo "

", $content, "
"; ?>

I want to once again draw your attention to the fact that this decision is not the only correct one. For example, the following code will produce the same result:

13 years ago

A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

array
[ GLOBALS ] => Array
[ GLOBALS ] => Array
* RECURSION *
[_POST] => Array()
[_GET] => Array()
[_COOKIE] => Array()
[ _FILES ] => Array()
)

[_POST] => Array()
[_GET] => Array()
[_COOKIE] => Array()
[ _FILES ] => Array()

)
?>

Notice that $_SERVER isn"t there. It seems that php only loads the superglobal $_SERVER if it is used somewhere. You could do this:

print"

" .htmlspecialchars(print_r(get_defined_vars(), true )) . "
" ;
print"
" .htmlspecialchars (print_r ($_SERVER , true )) . "
" ;
?>

And then $_SERVER will appear in both lists. I guess it "s not really a gotcha, because nothing bad will happen either way, but it"s an interesting curiosity nonetheless.

6 years ago

Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = "foo" ;
$bar = "bar" ;

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(), $vars);

echo "

"
;
print_r($vars);
echo "
" ;
?>

15 years ago

Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

function generateDebugReport ($method , $defined_vars , $email = "undefined" )(
// Function to create a debug report to display or email.
// Usage: generateDebugReport(method,get_defined_vars(),email);
// Where method is "browser" or "email".

// Create an ignore list for keys returned by "get_defined_vars".
// For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
// redundant (same as _POST, _GET)
// Also include vars you want ignored for security reasons - i.e. PHPSESSID.
$ignorelist =array("HTTP_POST_VARS" , "HTTP_GET_VARS" ,
"HTTP_COOKIE_VARS" , "HTTP_SERVER_VARS" ,
"HTTP_ENV_VARS" , "HTTP_SESSION_VARS" ,
"_ENV" , "PHPSESSID" , "SESS_DBUSER" ,
"SESS_DBPASS" , "HTTP_COOKIE" );

$timestamp = date("m/d/y h:m:s" );
$message = "Debug report created $timestamp \n" ;

// Get the last SQL error for good measure, where $link is the resource identifier
// for mysql_connect. Comment out or modify for your database or abstraction setup.
global $link ;
$sql_error = mysql_error($link);
if($sql_error )(
$message .= "\nMysql Messages:\n" . mysql_error($link);
}
// End MySQL

// Could use a recursive function here. You get the idea ;-)
foreach($defined_vars as $key => $val )(
if(is_array ($val ) && ! in_array ($key , $ignorelist ) && count ($val ) > 0 )(
$message .= "\n $key array (key=value):\n" ;
foreach($val as $subkey => $subval )(
if(! in_array ($subkey , $ignorelist ) && ! is_array ($subval ))(
$message .= $subkey . "=" . $subval . "\n" ;
}
elseif(! in_array ($subkey , $ignorelist ) && is_array ($subval ))(
foreach($subval as $subsubkey => $subsubval )(
if(! in_array ($subsubkey , $ignorelist ))(
$message .= $subsubkey . "=" . $subsubval . "\n" ;
}
}
}
}
}
elseif(!
is_array ($val ) && ! in_array ($key , $ignorelist ) && $val )(
$message .= "\nVariable " . $key. "=" . $val. "\n" ;
}
}

If($method == "browser" )(
echo nl2br($message);
}
elseif($method == "email" )(
if($email == "undefined" )(
$email = $_SERVER["SERVER_ADMIN"];
}

$mresult = mail ($email , "Debug Report for " . $_ENV [ "HOSTNAME" ]. "" , $message );
if($mresult == 1 )(
echo "Debug Report sent successfully.\n";
}
else(
echo "Failed to send Debug Report.\n";
}
}
}
?>

17 years ago

Simple routine to convert a get_defined_vars object to XML.

function obj2xml ($v , $indent = "" ) (
while (list($key , $val ) = each ($v )) (
if ($key == "__attr" ) continue;
// Check for __attr
if (is_object ($val -> __attr )) (
while (list($key2 , $val2 ) = each ($val -> __attr )) (
$attr .= " $key2 =\" $val2 \"" ;
}
}
else $attr = "" ;
if (is_array ($val ) || is_object ($val )) (
print(" $indent< $key$attr >\n");
obj2xml ($val , $indent . " " );
print(" $indent\n");
}
else print(" $indent< $key$attr >$val\n");
}
}

//Example object
$x -> name -> first = "John" ;
$x -> name -> last = "Smith" ;
$x -> arr [ "Fruit" ] = "Bannana" ;
$x -> arr [ "Veg" ] = "Carrot" ;
$y -> customer = $x ;
$y -> customer -> __attr -> id = "176C4" ;

$z = get_defined_vars();
obj2xml($z["y"]);
?>
will output:


John
Smith


Banana
carrot

11 years ago

As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

// define a variable
$my_var = "foo" ;

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars [ "my_var" ] = "bar" ;

echo $my_var , "\n" ;

?>

will output "foo" (the original value). It "d be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name )
{
$defined_vars [ $var_name ] =& $ $var_name ;
}

?>

1 year ago

I posted here before about "this" being in get_defined_vars.

It turns out it "s not always there but in certain cases it will inexplicably appear.

Php -r"
class Test(
public function a() (var_dump(array_keys(get_defined_vars()));$a = 123;)
public function b() (var_dump(array_keys(get_defined_vars()));$this;)
}
$t = new Test();
$t->a();
$t->b();
"

array()
array("this")

This does not happen in PHP 7.2 but will happen in PHP 5.6.

1 year ago

Some comments here point out that this function wont return references. It does however return names and names are "references".

I would not recommend the suggestions here that convert it to references.

public function x($a, $b, $c) (
foreach(array_keys(get_defined_vars()) as $key)
if($key !== "this")
$this->y($($key));
}

Public function y(&$input) (
$input++;
}

Instead of $() you can also use $$.

I have done some whacky things in my time to make extremely generic code but I"ve never had to do anything like the above. It might not even work (but should since it"s no different to $a[$key]).

You could also do $$key++ but I"ve never seen code like that which wasn"t horrifically bad (using dynamic where dynamic isn"t beneficial).

If you"re doing something like that then give it additional scrutiny.