`
hudeyong926
  • 浏览: 2016054 次
  • 来自: 武汉
社区版块
存档分类
最新评论

PHP变量的变量——可变变量

    博客分类:
  • PHP
 
阅读更多

php可变参数

<?php
/**
 *计算任意多个数的和,并返回计算后的结果
 */
function sum() { //这里的括号中没有定义任何参数
    echo "输入参数个数:",func_num_args(),"结果:"; //输出参数个数
    $total = 0;
    $varArray = func_get_args(); //使用func_get_args()来获取当前函数的所有实际传递参数,返回值为array类型
    foreach ($varArray as $index => $var) {
        $total += func_get_arg($index); //获取单个参数
        //$total += $var;
    }
    return $total;
}

/*****下面是调用示例*****/
echo sum(1, 3, 5); //计算1+3+5
echo sum(1, 2); //计算1+2
echo sum(1, 2, 3, 4); //计算1+2+3+4

/**
 *计算任意多个数的和,并返回计算后的结果
 */
function sum($a, $b) {
    return array_sum(func_get_args());
}
 

 

可变变量的概念:通过获取一个变量的值做为另外一个变量的名称来操作变量,就是可以变量。

<?php
$method = "save" . ucfirst($data_type['input_table']) . "_" . $file_info['file_type'];
$this->$method($file_info);

for ($i = 1; $i < 5; $i++) {
    $name = "name_" . $i;
    $$name = 'test' . $i;
}
$result = $this->_statement->{$method}($mode);
eval('$this->' . $_GET['flashreport'] . '();');

 

<?php   
$a  = 'hello' ;   //普通变量    
$$a  = 'world' ;  //可变变量 ,相当于 $hello='world';    
echo  "$a $hello" ;  //输出:hello world   
echo  $$a ;   //输出:world     
echo  "$a ${$a}" ;  //输出:hello world   
echo  "$a {$$a}" ;  //输出:hello world   
$string = "beautiful";
$time = "winter";
$str = 'This is a $string $time morning!';
echo $str. "<br />";

eval("\$str = \"$str\";");
echo $str;
This is a $string $time morning!
This is a beautiful winter morning! 
eval('$a=55;');
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics