1

次の問題があります。宣言された変数を持つファイルvariable.phpがあります:

<?php
  $animal = "cat";
?>

そして、この変数を関数で使用したいファイルb.php

<?php
  include_once 'a.php';

  function section()
  {
     $html = "<b>" . $animal "</b>";
     return $html;
  }
?>

関数を使用しているc.phpをファイルしますsection()

<?php
  require_once 'b.php';
  echo section();
?>

エラーメッセージがありますvariable $animal does not exist in file b.php。なぜ、そして私はここで何ができるのですか?

よろしく、ダグナ

4

5 に答える 5

8

変数には関数スコープがあります。$animal 関数内で変数を宣言しなかったため、関数section内では使用できませんsection

それを関数に渡して、そこで値を使用できるようにします。

function section($animal) {
   $html = "<b>" . $animal "</b>";
   return $html;
}

require_once 'a.php';
require_once 'b.php';
echo section($animal);
于 2012-06-14T14:52:08.217 に答える
3

関数に送信$animal;します:

function section($animal)
  {
     $html = "<b>" . $animal "</b>";
     return $html;
  }
于 2012-06-14T14:50:37.887 に答える
1
include_once 'a.php';

する必要があります

include_once 'variable.php';
于 2012-06-14T14:52:19.697 に答える
1

もう1つの方法は、次のようなクラスを使用することです。

class vars{
  public static $sAnimal = 'cat';
}

次に、関数で、その変数を次のように使用します。

public function section()
{
  return "<B>".vars::$sAnimal."</b>";
}
于 2012-06-14T14:56:44.017 に答える
0

定数を使用する場合は、PHPのdefine関数を使用できます。

a.php:

 <?php
    define("ANIMAL", "cat");
 ?>

b.php:

 <?php
    include_once 'a.php';
    function section() {
      $html = "<b>" . ANIMAL . "</b>";
      return $html;
    }
 ?>
于 2012-06-14T14:59:51.523 に答える