Ich möchte Variablen aus einem anderen Abschnitt von PHP auf einer Webseite verwenden. Hier ist ein Beispiel, was ich machen möchte:
<?php
$MyTitle = "Some Text";
?>
<html>
<head>
<title><?php echo $MyTitle; ?></title>
</head>
<body>Hello world</body>
</html>
Antworten:
1 für die Antwort № 1Du solltest benutzen einschließen(). Hier ist ein Beispiel dafür:
vars.php
<?php
$color = "green";
$fruit = "apple";
?>
test.php
echo "A $color $fruit"; // A
include "vars.php";
echo "A $color $fruit"; // A green apple
?>
1 für die Antwort № 2
Variablen müssen im "Geltungsbereich" des Dokuments sein, in dem Sie versuchen, die darin enthaltenen Variablen zu verwenden.
yourFile.php
<?php
$document = array("title"=>"My Test HTML Page!", "author"=>"Test");
?>
yourHtmlFile.php
<?php
include("yourFile.php");
?>
<h1>Welcome, <?= $document->title ?></h1>
<h2>Written By: <?= $document->author ?></h2>
In diesem Beispiel habe ich ein Array verwendet, da ich es sauberer finde.