在变量中使用变量
Using variable inside variable
我有以下 scenario.I 正在创建一个配置页面,我在一个地方设置格式。我在超过 10 php 页中使用了这种格式。
//Settings
$format = "$one $two $three";
$one = 1;
$two = 2;
$three = 3;
echo $format;
//This should output 1 2 3
现在,如果我想更改格式,我需要在所有 10 页中更改 "$two $one $three"
,我怎样才能在一个地方设置它并在多个地方重复使用它 place.Is 这可能在php ?
P.s :
我的场景:我有 settings.php ,我在其中设置 $format = "$one $two $three";
,我在所有 10 页中都包含 settings.php ....当我更改 $format
时settings.php 它应该反映在所有 10 页中.. 无需太多工作。
您应该编写一个函数来根据您的需要创建格式:
function createFormat($one, $two, $three)
{
return "$one $two $three";
}
然后,只要你需要格式,你就写:
$format = createFormat($one, $two, $three);
您可以使用可调用的方法做得更好(在 settings.php 中):
//define the function first, with references
$one = 0; $two = 0; $three = 0;
$format = function () use (&$one,&$two,&$three) { print "$one $two $three";};
在你做的下一个文件中
$one = 1; $two = 2; $three = 3;
$format();//will print "1 2 3"
$one = 2; $two = 5; $three = 6;
$format();//will print "2 5 6"
这可以工作,但你必须留意使用的引用(变量)
内联变量解析:
$one=1; $two=2; $three=3;
$format = "{$one} {$two} {$three}";
return $format;
我有以下 scenario.I 正在创建一个配置页面,我在一个地方设置格式。我在超过 10 php 页中使用了这种格式。
//Settings
$format = "$one $two $three";
$one = 1;
$two = 2;
$three = 3;
echo $format;
//This should output 1 2 3
现在,如果我想更改格式,我需要在所有 10 页中更改 "$two $one $three"
,我怎样才能在一个地方设置它并在多个地方重复使用它 place.Is 这可能在php ?
P.s :
我的场景:我有 settings.php ,我在其中设置 $format = "$one $two $three";
,我在所有 10 页中都包含 settings.php ....当我更改 $format
时settings.php 它应该反映在所有 10 页中.. 无需太多工作。
您应该编写一个函数来根据您的需要创建格式:
function createFormat($one, $two, $three)
{
return "$one $two $three";
}
然后,只要你需要格式,你就写:
$format = createFormat($one, $two, $three);
您可以使用可调用的方法做得更好(在 settings.php 中):
//define the function first, with references
$one = 0; $two = 0; $three = 0;
$format = function () use (&$one,&$two,&$three) { print "$one $two $three";};
在你做的下一个文件中
$one = 1; $two = 2; $three = 3;
$format();//will print "1 2 3"
$one = 2; $two = 5; $three = 6;
$format();//will print "2 5 6"
这可以工作,但你必须留意使用的引用(变量)
内联变量解析:
$one=1; $two=2; $three=3;
$format = "{$one} {$two} {$three}";
return $format;