Funktionen include

Funktionen include inkluderar och kör den angivna filen. Om filen inte hittas visas en varning, men skriptkörningen fortsätter. Som parameter tar funktionen sökvägen till filen.

Syntax

phpinclude 'path/to/file.php';

Exempel

Låt oss inkludera filen header.php och visa dess innehåll:

php<?php
  include 'header.php';
?>

Exempel

Låt oss försöka inkludera en fil som inte finns:

php<?php
  include 'nonexistent.php';
  echo "Script continues...";
?>

Resultat av kodkörning:

phpWarning: include(nonexistent.php): failed to open stream: No such file or directory
Script continues...

Exempel

Låt oss inkludera en fil med variabler och använda dem:

php<?php
  // config.php innehåller: $siteName = "My Site";
  include 'config.php';
  echo $siteName;
?>

Resultat av kodkörning:

php'My Site'

Se även

  • funktionen require,
    som liknar include, men orsakar ett fatalt fel om filen saknas
  • funktionen include_once,
    som inkluderar filen endast en gång