变量不存在

cad*_*108 1 php variables

我有以下问题.我有变量的文件variable.php:

<?php
  $animal = "cat";
?>
Run Code Online (Sandbox Code Playgroud)

并提交b.php文件,我想在函数中使用这个变量

<?php
  include_once 'a.php';

  function section()
  {
     $html = "<b>" . $animal "</b>";
     return $html;
  }
?>
Run Code Online (Sandbox Code Playgroud)

和文件c.php,我正在使用我的功能 section()

<?php
  require_once 'b.php';
  echo section();
?>
Run Code Online (Sandbox Code Playgroud)

我有一条错误消息variable $animal does not exist in file b.php.为什么以及我可以在这做什么?

最诚挚的问候,达格纳

dec*_*eze 8

变量具有功能范围.你没有声明变量$animal 里面你的section功能,所以它不是可用的内部section功能.

将其传递给函数以使值可用:

function section($animal) {
   $html = "<b>" . $animal "</b>";
   return $html;
}
Run Code Online (Sandbox Code Playgroud)
require_once 'a.php';
require_once 'b.php';
echo section($animal);
Run Code Online (Sandbox Code Playgroud)