DIGITAL4FRONT / CODE BASE

PHP MVC: Why Variables Are Missing from Included Views

Fix a PHP MVC form that refreshes without showing a calculation. Learn why the controller must return its result, how PHP include scope works, and how to pass validated data into a view.

Share

PHP MVC views do not automatically receive local variables created in another controller. In the original example, the form controller is never called, and its method never returns the calculated value. The fix is to process the request, return the result, and explicitly pass that result to the view controller before including the template.

Why the original result never appears

The entry point creates ControllerView and calls ctrView(), which includes mainView.php. It never executes ControllerForm::ctrForm(), so the calculation does not happen.

There is a second bug: ctrForm() stores the sum in a local $result variable but does not return it. Changing index.php to call ctrView(ControllerForm::ctrForm()) is not enough unless ctrForm() includes a return statement.

Finally, the template is included inside ControllerView::ctrView(). It can see local variables defined in that method, not unrelated variables defined inside ControllerForm::ctrForm(). A return value provides the bridge between them.

Complete working five-file example

Create this structure in a PHP-enabled web directory. The example uses no framework or database.

index.php
CONTROLLER/controllerForm.php
CONTROLLER/controllerView.php
MODEL/modelOperation.php
VIEW/mainView.php

1. Entry point: index.php

Load the classes and run the request through the form controller, then pass its output to the view controller.

php
<?php
declare(strict_types=1);

require_once __DIR__ . '/MODEL/modelOperation.php';
require_once __DIR__ . '/CONTROLLER/controllerForm.php';
require_once __DIR__ . '/CONTROLLER/controllerView.php';

$viewData = ControllerForm::ctrForm();

$mainView = new ControllerView();
$mainView->ctrView($viewData);

2. Model: MODEL/modelOperation.php

Keep the arithmetic in the model. It does not read POST data or produce HTML.

php
<?php
declare(strict_types=1);

final class ModelOperation
{
    public static function mdlOperation(float $num1, float $num2): float
    {
        return $num1 + $num2;
    }
}

3. Request controller: CONTROLLER/controllerForm.php

The controller validates submitted values and always returns the same data structure. Using an explicit null result distinguishes “not calculated yet” from a legitimate sum of zero.

php
<?php
declare(strict_types=1);

final class ControllerForm
{
    public static function ctrForm(): array
    {
        $data = [
            'num1' => '',
            'num2' => '',
            'result' => null,
            'error' => null,
        ];

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
            return $data;
        }

        $raw1 = $_POST['num1'] ?? null;
        $raw2 = $_POST['num2'] ?? null;

        if (!is_string($raw1) || !is_string($raw2)) {
            $data['error'] = 'Enter two valid numbers.';
            return $data;
        }

        $data['num1'] = trim($raw1);
        $data['num2'] = trim($raw2);

        if ($data['num1'] === '' || $data['num2'] === '') {
            $data['error'] = 'Both numbers are required.';
            return $data;
        }

        $num1 = filter_var($data['num1'], FILTER_VALIDATE_FLOAT);
        $num2 = filter_var($data['num2'], FILTER_VALIDATE_FLOAT);

        if ($num1 === false || $num2 === false) {
            $data['error'] = 'Enter two valid numbers.';
            return $data;
        }

        $result = ModelOperation::mdlOperation($num1, $num2);

        if (!is_finite($result)) {
            $data['error'] = 'The result is outside the supported range.';
            return $data;
        }

        $data['result'] = $result;
        return $data;
    }
}

4. View controller: CONTROLLER/controllerView.php

The view controller makes variables available in its own scope before including the template.

php
<?php
declare(strict_types=1);

final class ControllerView
{
    public function ctrView(array $data): void
    {
        $num1 = $data['num1'];
        $num2 = $data['num2'];
        $result = $data['result'];
        $error = $data['error'];

        require __DIR__ . '/../VIEW/mainView.php';
    }
}

5. Template: VIEW/mainView.php

Preserve the submitted values after a POST. Escape displayed strings so user input is not interpreted as HTML.

php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Numerical operation</title>
</head>
<body>
    <h1>Numerical operation</h1>
    <form method="post">
        <label for="num1">Number 1</label>
        <input id="num1" type="number" step="any" name="num1"
            value="<?= htmlspecialchars($num1, ENT_QUOTES, 'UTF-8') ?>" required>

        <label for="num2">Number 2</label>
        <input id="num2" type="number" step="any" name="num2"
            value="<?= htmlspecialchars($num2, ENT_QUOTES, 'UTF-8') ?>" required>

        <button type="submit">Add</button>
    </form>

    <?php if ($error !== null): ?>
        <p role="alert"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p>
    <?php endif; ?>

    <?php if ($result !== null): ?>
        <p>The result is: <?= htmlspecialchars((string) $result, ENT_QUOTES, 'UTF-8') ?></p>
    <?php endif; ?>
</body>
</html>

How include scope actually works

PHP executes an included file in the variable scope of the line that includes it. Because mainView.php is required inside ctrView(), it can use $result, $error, $num1 and $num2 defined inside that method.

It cannot directly see a local $result inside ctrForm(). Local variables are not shared automatically between methods. Likewise, requiring a class file makes the class definition available; it does not instantiate the class or call a method.

The original answer's suggested expression, ctrView(ControllerForm::ctrForm()), is a valid way to pass the result only if ctrForm() actually returns that result. Our example returns a complete view-data array so the form values and validation message also survive the request.

Checks and limitations

Run the application through a PHP-enabled web server, not by opening index.php as a local file. Try 2 plus 3, 0 plus 0, a negative number, a decimal, an empty field and invalid input. The result should appear for valid submissions, and inputs should retain their values when validation fails.

This is intentionally a small teaching example, not a full MVC framework. Real applications normally add routing, dependency management, tests and dedicated response handling. Floating-point arithmetic is appropriate for this demonstration but not exact financial calculations; use integer minor units or a decimal arithmetic library when money is involved.

For more background, consult the PHP include documentation and PHP variable scope documentation.

WhatsApp us