在 PHP 中打印变量不起作用


Printing a variable in PHP does not work

我有这段代码:

<?php
  $userid = $me['id'];
  function showifuserexists() {
?>
<html>
  <head></head>
<body>
  <a href="file.php?element1=aaa&userid=<?php print $userid; ?>">
</body>
</html>
<?php
} 
?>

由于某种原因,我无法让 php $userid显示在 html 链接中。我也试过echo。帮助?

你应该阅读变量范围。

函数中的$userid与函数外的$userid不同 - 它具有不同的scope。你可以使变量成为全局变量,但这不是真正的好做法,尤其是在这种上下文中。

我不太确定你想实现什么;但我想。

function showifuserexists($userid=null) {
    echo '<a href="file.php?element1=aaa&userid=' . $userid . '"> ... </a>';
    // functions should *generally* return output, but for examples sake
}

然后你会做:

showifuserexists($me['id']);

例如。但是你的要求并不是那么清楚。

如果不使用内联创建的函数来实现这样的简单行为,您很可能会好得多。只需使用一个简单的 if 语句

<?php
    $userid = $me['id'];
    if (null !== $userid) {
?>
<html>
  <head></head>
<body>
  <a href="file.php?element1=aaa&userid=<?php print $userid; ?>">
</body>
</html>
<?php
    }
?>

旁注:您原始帖子中的问题是 - 就像许多其他人已经解释的那样 - $userid在您的函数范围之外定义,使其在此函数范围内不可用。

$userid

showifuserexists()中不存在。使用 global 告诉函数变量在外部找到。

不能在函数内部访问变量$userid。您可以通过将变量作为函数参数传递来获取值。

示例代码:

<?php
  $userid = 1;
  function showifuserexists($userid) {
?>
  <html>
  <head></head>
  <body>
      <a href="file.php?element1=aaa&userid=<?php echo $userid?>" >
  </body>
  </html>
<?php
}
showifuserexists($userid);
?>

希望这对您有所帮助。