cadi2108
cadi2108

Reputation: 1280

Variable doesn't exist

I have following problem. I have file variable.php with declared variable:

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

And file b.php, where I want to use this variable in a function

<?php
  include_once 'a.php';

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

and file c.php where I'm using my function section()

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

I have an error message, that variable $animal does not exist in file b.php. Why and what can I do here?

Best regards, Dagna

Upvotes: 1

Views: 404

Answers (5)

mgraph
mgraph

Reputation: 15338

send $animal; to the function:

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

Upvotes: 3

TeaCupApp
TeaCupApp

Reputation: 11452

include_once 'a.php';

should be

include_once 'variable.php';

Upvotes: 1

comfortablejohn
comfortablejohn

Reputation: 645

If it is meant to be a constant, you could use PHP's define function.

a.php:

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

b.php:

 <?php
    include_once 'a.php';
    function section() {
      $html = "<b>" . ANIMAL . "</b>";
      return $html;
    }
 ?>

Upvotes: 0

Anton
Anton

Reputation: 1061

One more alternative is to use classes, like:

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

then in your functions, use that variable with:

public function section()
{
  return "<B>".vars::$sAnimal."</b>";
}

Upvotes: 1

deceze
deceze

Reputation: 522032

Variables have function scope. You did not declare the variable $animal inside your section function, so it's not available inside the section function.

Pass it into the function to make the value available there:

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

require_once 'a.php';
require_once 'b.php';
echo section($animal);

Upvotes: 8

Related Questions