<?php
//You can even add more Dollar Signs
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
//... and so on ...//
?>Променливи на променливи
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Променливи на променливи
Референца за `language.variables.variable.php` со подобрена типографија и навигација.
Променливи на променливи
Понекогаш е погодно да може да имате имиња на променливи што се менуваат. Тоа е, име на променлива што може да се постави и користи динамички. Нормална променлива се поставува со изјава како што е:
<?php
$a = 'hello';
?>Понекогаш е погодно да се имаат променливи имиња на променливи. Тоа е, име на променлива што може да се постави и користи динамички. Нормална променлива се поставува со изјава како што е: helloПроменлива променлива зема вредност од променлива и ја третира како име на променлива. Во горниот пример,
<?php
$$a = 'world';
?>може да се користи како име на променлива со користење на два знака за долар. т.е. $a Во овој момент се дефинирани и складирани две променливи во PHP симболичкото дрво: $hello со содржина "hello" и
<?php
echo "$a {$$a}";
?>со содржина "world". Затоа, оваа изјава:
<?php
echo "$a $hello";
?>го произведува истиот излез како: т.е. и двете произведуваат:.
hello world
$$a[1] За да се користат променливи променливи со низи, мора да се реши проблем со двосмисленост. Тоа е, ако парсерот види
$a[1] тогаш треба да знае дали
$$a беше наменето да се користи како променлива, или ако [1]
се сакаше како променлива и потоа ${$a[1]} индекс од таа променлива. Синтаксата за решавање на оваа двосмисленост е:
${$a}[1] за првиот случај и
за вториот. $foo->$barСвојствата на класата исто така може да се пристапат со користење на имиња на променливи својства. Името на променливото својство ќе се реши во опсегот од кој е направен повикот. На пример, ако постои израз како $bar , тогаш локалниот опсег ќе се испита за $fooи неговата вредност ќе се користи како име на својството на $bar е пристап до низа.
Фигурните загради може да се користат и за јасно разграничување на името на својството. Тие се најкорисни кога се пристапува до вредности во својство што содржи низа, кога името на својството е составено од повеќе делови, или кога името на својството содржи знаци што инаку не се валидни (на пр. од json_decode() or SimpleXML).
Пример #1 Пример за променливо својство
<?php
class Foo {
public $bar = 'I am bar.';
public $arr = ['I am A.', 'I am B.', 'I am C.'];
public $r = 'I am r.';
}
$foo = new Foo();
$bar = 'bar';
$baz = ['foo', 'bar', 'baz', 'quux'];
echo $foo->$bar . "\n";
echo $foo->{$baz[1]} . "\n";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->{$arr[1]} . "\n";
echo $foo->{$arr}[1] . "\n";
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
I am bar. I am bar. I am bar. I am r. I am B.
Ве молиме имајте предвид дека променливите променливи не можат да се користат со PHP-овите
Суперглобални низи
во функции или методи на класа. Променливата $this
е исто така специјална променлива на која не може динамички да се повикува.
Белешки од корисници 11 белешки
It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:
<?php
// 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.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;While not relevant in everyday PHP programming, it seems to be possible to insert whitespace and comments between the dollar signs of a variable variable. All three comment styles work. This information becomes relevant when writing a parser, tokenizer or something else that operates on PHP syntax.
<?php
$foo = 'bar';
$
/*
I am complete legal and will compile without notices or error as a variable variable.
*/
$foo = 'magic';
echo $bar; // Outputs magic.
?>
Behaviour tested with PHP Version 5.6.19If 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:
<?php
$price_for_monday = 10;
$price_for_tuesday = 20;
$price_for_wednesday = 30;
$today = 'tuesday';
$price_for_today = ${ 'price_for_' . $today};
echo $price_for_today; // will return 20
?>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
<?php
$vars = ['id'=>'user_id','email'=>'user_email'];
validateVarsFunction($vars);
function validateVarsFunction($vars){
//$vars['id']=34; <- does not work
// define allowed variables
$user_id=21;
$user_email='[email protected]';
echo $vars['id']; // prints name of variable: user_id
echo ${$vars['id']}; // prints 21
echo 'Email: '.${$vars['email']}; // print [email protected]
// we don't have the name of the variables before declaring them inside the function
}
?>PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2
<?php
class Foo {
public function hello() {
echo 'Hello world!';
}
}
$my_foo = 'Foo';
$a = new $my_foo();
$a->hello(); //prints 'Hello world!'
?>
Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3
<?php
class Foo {
public static function hello() {
echo 'Hello world!';
}
}
$my_foo = 'Foo';
$my_foo::hello(); //prints 'Hello world!'
?>One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.
<?php
define('ONE', 1);
function one() {
return 1;
}
$one = 1;
${"foo$one"} = 'foo';
echo $foo1; // foo
${'foo' . ONE} = 'bar';
echo $foo1; // bar
${'foo' . one()} = 'baz';
echo $foo1; // baz
?>
This syntax doesn't work for functions:
<?php
$foo = 'info';
{"php$foo"}(); // Parse error
// You'll have to do:
$func = "php$foo";
$func();
?>
Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.Variable Class Instantiation with Namespace Gotcha:
Say you have a class you'd like to instantiate via a variable (with a string value of the Class name)
<?php
class Foo
{
public function __construct()
{
echo "I'm a real class!" . PHP_EOL;
}
}
$class = 'Foo';
$instance = new $class;
?>
The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.)
<?php
namespace MyNamespace;
class Foo
{
public function __construct()
{
echo "I'm a real class!" . PHP_EOL;
}
}
$class = 'MyNamespace\Foo';
$instance = new $class;
?>there is a comment, that this does not work:
<?php
$foo = 'info';
{"php$foo"}(); // Parse error
?>
however this works (at least as tested in 8.3.30):
<?php
$foo = 'info';
"php$foo"(); // works
?>These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.
<?php
$_POST['asdf'] = 'something';
function test() {
// NULL -- not what initially expected
$string = '_POST';
var_dump(${$string});
// Works as expected
var_dump(${'_POST'});
// Works as expected
global ${$string};
var_dump(${$string});
}
// Works as expected
$string = '_POST';
var_dump(${$string});
test();
?>