H
H
helixly2015-11-17 17:05:43
PHP
helixly, 2015-11-17 17:05:43

Using $$ in PHP?

In the source code of Bitrix, I came across such a thing

if ($REQUEST_METHOD=="POST" && strlen($Update)>0)
{
  foreach($arAllOptions as $option)
  {
    $name = $option[0];
    $val = $$name;
    COption::SetOptionString("main", $name, $val);
  }
}

The code has been shortened a bit, leaving the very essence. This is where the changes from the form are saved. $option[0] stores the name of the input. Actually, I had previously encountered variable variables and the $$ construction, but it is not entirely clear how this variable is formed. For example, such data comes
$_REQUEST["foo"] = "bar".
It turns out that I can display the value like this:
echo $foo \\ выведет bar
Of course, I have not been familiar with PHP for so long, but this is the first time I encounter this. Tell me please, is this a feature of the language, or does Bitrix create such variables somewhere inside?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
E
Elios, 2015-11-17
@helixly

And what does Bitrix have to do with it, this is a classic way of using named variables

$array = ['title'=>'TITLE','slug'=>'URL','contet'=>'CONTENT.....'];

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

echo $title; // TITLE
echo $slug; // URL
echo $contet; // CONTENT.....

M
Max, 2015-11-17
@AloneCoder

php.net/manual/en/language.variables.variable.php

A
Alexander Latyshev, 2015-11-17
@magalex

You have found the absolutely correct "joke" of Bitrix, it's "ugly" :) it creates such variables with this line:
$val = $$name;

V
Vladislav Kopylov, 2015-11-17
@kopylov_vlad

These are variable variables, here is an example

<?
$first = "second";
$second = "third";
echo $first; //second
echo "\n";
echo $$first; //third
?>

N
Nick Murzin, 2015-11-17
@R0s0maxa

A classic example of such things

class Foo {
  public $deepest = 10;
  
  public function __toString()
  {
    return 'deep';
  }
}
$deeper = 'deepest';
$deep = 'deeper';
$b = new Foo();
echo $b->$$$b;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question