Skip to content
Advertisement

Can’t access variable from an included php script

I am trying to access a variable $defaultPath from the php script that I have included.

However, when i am trying to echo the variable there is an error stating

undefined variable

. The php script is basically a nav bar (let’s call it navbar.php) and this includes the helper.php which is where the variable $defaultPath is located. Moreover, the navbar.php is included in index.php in which index.php also includes helper.php. I used include_once to include the helper.php in both navbar.php and index.php but only index.php can echo the variable but not navbar.php

Here are the codes: Navbar.php

<?php 
    include_once __DIR__ . '/../../helpers/helper.php';

    echo $defaultPath . "</br>";

?>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Interactive Digital Experience</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/capstone-project/style.css"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
        <a class="navbar-brand mb-0 h1" href=<?php echo pageUrl("index.php", $defaultPath)?>>ICT Open House</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse justify-content-end" id="navbarNavAltMarkup">
            <div class="navbar-nav">
                <a class="nav-item nav-link" href="<?php echo pageUrl("index.php", $defaultPath) ?>">Courses<span class="sr-only">(current)</span></a>
                <a class="nav-item nav-link" href="<?php echo pageUrl("quiz.php", $defaultPath) ?>">Course Quiz</a>
                <a class="nav-item nav-link" href="<?php echo pageUrl("tour.php", $defaultPath) ?>">Tour Map</a>
            </div>
        </div>
    </div>
</nav>

Helper.php

<?php

$defaultPath = ($_SERVER['SERVER_NAME'] == 'localhost') ? '/capstone-project/' : '/' ;

function subview($file) {
    $file =  __DIR__ . '/../views/sub-views/'. $file;
    include_once $file;
}

function cssPath($file, $defaultPath) {
    $hrefPath = $defaultPath .'assets/css/'. $file;
    return $hrefPath;
}

function jsPath($file, $defaultPath) {
    $hrefPath = $defaultPath . 'assets/js/'. $file;
    return $hrefPath;
}

function pageUrl($file, $defaultPath) {
    $httpProtocol = !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http' : 'https';
    $url = $httpProtocol . '://' . $_SERVER['HTTP_HOST'] . $defaultPath;
    if ($file !== 'index.php') {
        $url .= 'views/' . $file;
    }
    return $url;
}
?>

Index.php

<?php 
    include __DIR__.'/helpers/helper.php';
?>

<!DOCTYPE html>
<html lang="en">
    <?php subview('header.php') ?>
    <main class="container">
        <header>
            <h1>Fullscreen Landing Page</h1>
        </header>
        <section class="courses">
            <div class="row justify-content-center">
                <div class="col-xs-6 col-md-4 bg-primary">Course 1</div>
                <div class="col-xs-6 col-md-4 bg-primary">Course 2</div>
                <div class="col-xs-6 col-md-4 bg-primary">Course 3</div>
                <div class="col-xs-6 col-md-4 bg-primary">Course 4</div>
                <div class="col-xs-6 col-md-4 bg-primary">Course 5</div>
            </div>

        </section>
    </main>

    <?php subview('footer.php') ?>
</html>

* What I have tried * I tried changing it back to include but error occurs because of duplicate functions.

I also tried echo-ing the the $defaultPath variable in index.php and there are no undefined error but when i try to do it in navbar.php it gives me undefined sadly

Note: I am not trying to access the variable inside a function scope

Advertisement

Answer

The execution is:

// index.php
include __DIR__.'/helpers/helper.php';

helper.php has thereby been included once.

// index.php
subview('header.php')

This establishes a new function scope.

// function subview
include_once $file;

Includes the header which includes the navbar, all within the scope of subview.

// navbar.php
include_once __DIR__ . '/../../helpers/helper.php';

Doesn’t do anything, since helper.php has already been included previously.

// navbar.php
echo $defaultPath . "</br>";

Tries to echo a variable which is not in scope and hasn’t been included.

Functions aren’t scoped; if the file which defines the function has been included once anywhere, they’re available globally everywhere. In fact, if you would try to include the file again, you’d run into an error about trying to redefine existing functions. That’s exactly what include_once is for, to avoid that problem.

You could use the global keyword to access your globally included and defined variable, or you could rethink your file structure to separate define-once functions from variables which need to be included multiple times.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement