【问题标题】:What is the difference between $name and $$name?$name 和 $$name 有什么区别?
【发布时间】:2014-01-22 17:05:25
【问题描述】:

我一直在处理电子邮件表单并遇到了一个问题。

<?php 
 $to = $_REQUEST['sendto'] ; 
 $from = $_REQUEST['Email'] ; 
 $name = $_REQUEST['Name'] ; 
 $headers = "From: $from"; 
 $subject = "Web Contact Data"; 

 $fields = array(); 
 $fields{"Name"} = "Name"; 
 $fields{"Company"} = "Company"; 
 $fields{"Email"} = "Email"; 
 $fields{"Phone"} = "Phone"; 
 $fields{"list"} = "Mailing List"; 
 $fields{"Message"} = "Message"; 

 $body = "We have received the following information:\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } 

 $headers2 = "From: noreply@YourCompany.com"; 
 $subject2 = "Thank you for contacting us"; 
 $autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.oursite.com";

 if($from == '') {print "You have not entered an email, please go back and try again";} 
 else { 
 if($name == '') {print "You have not entered a name, please go back and try again";} 
 else { 
 $send = mail($to, $subject, $body, $headers); 
 $send2 = mail($from, $subject2, $autoreply, $headers2); 
 if($send) 
 {header( "Location: http://www.YourDomain.com/thankyou.html" );} 
 else 
 {print "We encountered an error sending your mail, please notify webmaster@YourCompany.com"; } 
 }
}
 ?> 

我已尝试运行它,但 $name 变量一直出错。我做了一些研究,发现我也可以使用$$name。我跑了一遍但没有用,所以我决定我应该更改脚本的其他部分。我需要知道是$name 还是$$name。我做了一些研究,发现$$name是一个引用变量,而$name只是一个变量。我需要知道每一个的结果是什么,以及我应该使用哪一个。

【问题讨论】:

  • 你一直有什么错误?

标签: php forms email variables


【解决方案1】:

$$name 可能不是您要查找的内容

$abc = 'def';
$name = 'abc';

echo $name;  // this will output abc
echo $$name; // this will output def

您可以从http://www.php.net/manual/en/language.variables.variable.php 阅读有关 php 变量的信息

【讨论】:

    【解决方案2】:

    它是一个变量变量:

    $x = 'foo';
    $foo = 'bar';
    $$x = 'baz';
    echo "$x $foo"; // outputs 'foo baz', not 'foo bar';
    

    $$var 基本上是在说“获取 $var 的内容,并将该内容用作变量的名称,然后分配给该变量”。

    【讨论】:

      【解决方案3】:

      看来你要使用数组

      $fields = array(); 
      $fields["Name"] = $_REQUEST['Name']; 
      $fields["Company"] = $_REQUEST['Company']; 
      $fields["Email"] = $_REQUEST['Email']; 
      $fields["Phone"] = $_REQUEST['Phone']; 
      $fields["Mailing list"] = $_REQUEST['List']; 
      $fields["Message"] = $_REQUEST["Message"]; 
      

      您的脚本现在可以正常工作了。

      如果您想包含来自 $_REQUEST 的数据,请尝试这种方式。

      您也可以粘贴php表单,我们可以提出更优化的解决方案

      【讨论】:

      • 抱歉,这不是我想要的。我想知道我应该在我的脚本中使用哪一个
      【解决方案4】:

      当您在变量前面添加 $ 时,您将其设为动态变量。如果您希望能够在变量之间切换,这很方便。

      【讨论】:

        猜你喜欢
        • 2011-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多