简体   繁体   中英

PHP: Is it possible to modify varibles of an included php file?

I am new to php. I have a header.php with variables which I want to be uniquely set depending on which php page includes the header.php. I want each page that loads the header to display unique data in the header - current page info.
Currently I have something like the following:

header.php

     <?php $pageInfo = "";?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="css/header.css">
        <title></title>
    </head>
    <body>
        <div id="header-box">
            <div id="header-wrapper">
                <div id="logo-box">
                </div>
                <div id="info-box">
                    <div>
                        <p><?php echo $pageInfo ?></p>                      
                   </div>
                </div>
        </div>
    </body>
 </html>

page1.php

<body>
    <div><?php $pageInfo = ":D"; require 'shared/header.php'; ?></div>
    <div><?php include 'shared/menu.php';?></div>
</body>

Yes that is possible. Include works like as you have have merged multiple pages (Scripts) into one. So if you want to change the value of variables in header.php before including header.php define them.

ex:

<?php 
$pageInfo  = 'Test page';
require_once 'header.php';
?>

Note: Do not declare $pageInfo = '' in header.php else it will over write it. You can do as follow in header.php:

if(!isset($pageInfo)) {
 $pageInfo = '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM