【问题标题】:define variable in file_get_contents在 file_get_contents 中定义变量
【发布时间】:2012-10-18 13:58:12
【问题描述】:

我有这个代码

<?php
$a1 = 'http://www.hamooz.com';
$a2 = 'http://www.myegy.com';
$a3 = 'http://www.tech-wd.com/wd';
$num = rand(1,3);

$numb =  '$a'.$num;

echo file_get_contents($numb);
?>

问题看起来像:

警告:file_get_contents($a3) [function.file-get-contents]:无法打开流:第 9 行的 C:\xampp\htdocs\ttt\bessah.php 中没有这样的文件或目录

【问题讨论】:

    标签: php


    【解决方案1】:

    您需要做$numb = ${'a'.$num};,但使用数组解决方案作为@Pekka 的答案。

    【讨论】:

      【解决方案2】:

      可变变量是一种不好的做法。请改用数组。

      <?php
      
      $a = array();
      $a[] = 'http://www.hamooz.com';
      $a[] = 'http://www.myegy.com';
      $a[] = 'http://www.tech-wd.com/wd';
      $num = rand(0,2);
      
      $numb = $a[$num];
      
      echo file_get_contents($numb);
      ?>
      

      然而,对于这个特定的任务,还有一个shortcut

      array_rand ( )

      从数组中选择一个或多个随机条目,并返回随机条目的一个(或多个)键。

      【讨论】:

      • @AD7six 是的。这更多是出于教学目的,但绝对需要提及array_rand,我会添加它。
      【解决方案3】:

      我同意@Pekka 你会让你的代码复杂化, 但如果你绝对想使用动态变量,你可以这样做:

      <?php
      $a1="hello";
      $b=1;
      echo ${"a$b"};
      ?>
      

      【讨论】:

      • 这是一个很好的混淆方法。
      猜你喜欢
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 2016-03-17
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多