Php переменная содержит переменную

Php переменная содержит переменную

Переменные в PHP представлены знаком доллара с последующим именем переменной. Имя переменной чувствительно к регистру.

Имена переменных соответствуют тем же правилам, что и остальные наименования в PHP. Правильное имя переменной должно начинаться с буквы или символа подчёркивания и состоять из букв, цифр и символов подчёркивания в любом количестве. Это можно отобразить регулярным выражением: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Замечание: Под буквами здесь подразумеваются символы a-z, A-Z и байты от 128 до 255 ( 0x80-0xff ).

Замечание: $this — это специальная переменная, которой нельзя ничего присваивать. До PHP 7.1.0 было возможно косвенное присвоение (например, с использованием переменных переменных).

Для информации о функциях работы с переменными обращайтесь к разделу функций работы с переменными.

$var = ‘Боб’ ;
$Var = ‘Джо’ ;
echo » $var , $Var » ; // выведет «Боб, Джо»

$ 4site = ‘ещё нет’ ; // неверно; начинается с цифры
$_4site = ‘ещё нет’ ; // верно; начинается с символа подчёркивания
$täyte = ‘mansikka’ ; // верно; ‘ä’ это (Расширенный) ASCII 228.
?>

По умолчанию переменные всегда присваиваются по значению. То есть, когда вы присваиваете выражение переменной, все значение оригинального выражения копируется в эту переменную. Это означает, к примеру, что после того как одной переменной присвоено значение другой, изменение одной из них не влияет на другую. Дополнительную информацию об этом способе присвоения смотрите в разделе Выражения.

PHP также предлагает иной способ присвоения значений переменным: присвоение по ссылке. Это означает, что новая переменная просто ссылается (иначе говоря, «становится псевдонимом» или «указывает») на оригинальную переменную. Изменения в новой переменной отражаются на оригинале, и наоборот.

Для присвоения по ссылке, просто добавьте амперсанд (&) к началу имени присваиваемой (исходной) переменной. Например, следующий фрагмент кода дважды выводит ‘ Меня зовут Боб ‘:

$foo = ‘Боб’ ; // Присваивает $foo значение ‘Боб’
$bar = & $foo ; // Ссылка на $foo через $bar.
$bar = «Меня зовут $bar » ; // Изменение $bar.
echo $bar ;
echo $foo ; // меняет и $foo.
?>

Важно отметить, что по ссылке могут быть присвоены только именованные переменные.

$foo = 25 ;
$bar = & $foo ; // Это верное присвоение.
$bar = &( 24 * 7 ); // Неверно; ссылка на неименованное выражение.

Хорошей практикой считается инициализировать переменные, хотя в PHP это и не является обязательным требованием. Неинициализированные переменные принимают значение по умолчанию в зависимости от их типа, который определяется из контекста их первого использования: булевы принимают значение false , целые числа и числа с плавающей точкой — ноль, строки (например, при использовании в echo ) — пустую строку, а массивы становятся пустыми массивами.

Пример #1 Значения по умолчанию в неинициализированных переменных

// Неустановленная И не имеющая ссылок (то есть без контекста использования) переменная; выведет NULL
var_dump ( $unset_var );

// Булевое применение; выведет ‘false’ (Подробнее по этому синтаксису смотрите раздел о тернарном операторе)
echo $unset_bool ? «true\n» : «false\n» ;

Читайте также:  Java required что это

// Строковое использование; выведет ‘string(3) «abc»‘
$unset_str .= ‘abc’ ;
var_dump ( $unset_str );

// Целочисленное использование; выведет ‘int(25)’
$unset_int += 25 ; // 0 + 25 => 25
var_dump ( $unset_int );

// Использование в качестве числа с плавающей точкой (float); выведет ‘float(1.25)’
$unset_float += 1.25 ;
var_dump ( $unset_float );

// Использование в качестве массива; выведет array(1) < [3]=>string(3) «def» >
$unset_arr [ 3 ] = «def» ; // array() + array(3 => «def») => array(3 => «def»)
var_dump ( $unset_arr );

// Использование в качестве объекта; создаёт новый объект stdClass (смотрите http://www.php.net/manual/ru/reserved.classes.php)
// Выведет: object(stdClass)#1 (1) < ["foo"]=>string(3) «bar» >
$unset_obj -> foo = ‘bar’ ;
var_dump ( $unset_obj );
?>

Полагаться на значения по умолчанию неинициализированных переменных довольно проблематично при включении файла в другой файл, использующий переменную с таким же именем. В случае работы с неинициализированной переменной вызывается ошибка уровня E_WARNING (до PHP 8.0.0 выбрасывалась ошибка уровня E_NOTICE ), за исключением случая добавления элементов в неинициализированный массив. Для обнаружения инициализации переменной может быть использована языковая конструкция isset() .

User Contributed Notes 5 notes

This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn’t exist by using isset(). This returns true provided the variable exists and isn’t set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

print isset( $a ); // $a is not set. Prints false. (Or more accurately prints ».)
$b = 0 ; // isset($b) returns true (or more accurately ‘1’)
$c = array(); // isset($c) returns true
$b = null ; // Now isset($b) returns false;
unset( $c ); // Now isset($c) returns false;
?>

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it’s automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

$a_bool = true ; // a boolean
$a_str = ‘foo’ ; // a string
?>

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g Booleans default to FALSE, integers and floats default to zero, strings to the empty string », arrays to the empty array.

A variable can be tested for emptiness using empty();

$a = 0 ; //This isset, but is empty
?>

Unset variables are also empty.

empty( $vessel ); // returns true. Also $vessel is unset.
?>

Everything above applies to array elements too.

$item = array();
//Now isset($item) returns true. But isset($item[‘unicorn’]) is false.
//empty($item) is true, and so is empty($item[‘unicorn’]

Читайте также:  Конвертировать json to html

$item [ ‘unicorn’ ] = » ;
//Now isset($item[‘unicorn’]) is true. And empty($item) is false.
//But empty($item[‘unicorn’]) is still true;

$item [ ‘unicorn’ ] = ‘Pink unicorn’ ;
//isset($item[‘unicorn’]) is still true. And empty($item) is still false.
//But now empty($item[‘unicorn’]) is false;
?>

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.

Источник

Php переменная содержит переменную

It may be worth specifically noting, if variable names follow some kind of «template,» they can be referenced like this:

// Given these variables .
$nameTypes = array( «first» , «last» , «company» );
$name_first = «John» ;
$name_last = «Doe» ;
$name_company = «PHP.net» ;

// Then this loop is .
foreach( $nameTypes as $type )
print $ < "name_ $type " >. «\n» ;

// . equivalent to this print statement.
print » $name_first \n $name_last \n $name_company \n» ;
?>

This is apparent from the notes others have left, but is not explicitly stated.

In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
array(‘index’=>’value’,’index’=>’value’);
index = reference to variable to be used within function
value = name of the variable to be used within function

$vars = [ ‘id’ => ‘user_id’ , ’email’ => ‘user_email’ ];

function validateVarsFunction ( $vars )

//$vars[‘id’]=34; // define allowed variables
$user_id = 21 ;
$user_email = ’email@mail.com’ ;

echo $vars [ ‘id’ ]; // prints name of variable: user_id
echo $< $vars [ 'id' ]>; // prints 21
echo ‘Email: ‘ .$< $vars [ 'email' ]>; // print email@mail.com

// we don’t have the name of the variables before declaring them inside the function
>
?>

The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It’s a kind of magic 🙂 This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking «$userName». You may easily omit:
$a = ‘username’;
echo $$a;

If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

$price_for_monday = 10 ;
$price_for_tuesday = 20 ;
$price_for_wednesday = 30 ;

$price_for_today = $< 'price_for_' . $today >;
echo $price_for_today ; // will return 20
?>

PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

class Foo public function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$a = new $my_foo ();
$a -> hello (); //prints ‘Hello world!’
?>

Читайте также:  Custom php code in wordpress

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

class Foo public static function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$my_foo :: hello (); //prints ‘Hello world!’
?>

You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: —

foreach ( $array as $key => $value )
$ $key = $value ;
>

?>

This however would be reinventing the wheel when you can simply use:

extract ( $array , EXTR_OVERWRITE );
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: —

$array =array( «one» => «First Value» ,
«two» => «2nd Value» ,
«three» => «8»
);

extract ( $array , EXTR_PREFIX_ALL , «my_prefix_» );

?>

This would create variables: —
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: —
«First Value», «2nd Value» and «8» respectively

Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won’t need something this convolute. In this example, I needed to load an array with dynamically named objects — (yes, this has some basic Object Oriented programming, please bare with me..)

// this is only a skeletal example, of course.
$object_array = array();

// assume the $input array has tokens for parsing.
foreach ( $input_array as $key => $value ) <
// test to ensure the $value is what we need.
$obj = «obj» . $key ;
$ $obj = new Obj ( $value , $other_var );
Array_Push ( $object_array , $ $obj );
// etc..
>

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven’t fully tested the implimentation of the objects. The scope of a variable-variable’s object attributes (get all that?) is a little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

//.
foreach( $array as $key => $object )

echo $key . » — » . $object -> print_fcn (). »
\n» ;

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.

Источник

Оцените статью