Can't use same variable on 2 includes files on same page?

I have a public static function in the app/Controllers/App.php file that returns a true or null value.

At the top in the header I have $var = App::name_of_function() to get the value from the controller.

In my first header include I’m able to use $var == true and the variable is found.

However, in the footer, I’m also doing the same check but $var is showing “Notice : Undefined variable:”

Does anyone know how to be able to use the same variable twice in 2 different include files?

Thanks in advance.

You haven’t said what version of Sage you’re using, so the exact process to get what you want might vary a bit. I’m assuming you’re using Blades? If so, the @include directive in Blade doesn’t necessarily work like include() in PHP, so it’s risky to assume it will. What you’re doing probably isn’t working because you’re assuming that all all your @includes are basically pulled together to make a “single script” (as include() would do in plain PHP) but this isn’t what happens. $var exists in the scope of your header, but it doesn’t exist “above” it (i.e. in files the @include('headerFileName')). Because your footer is not @included from withing your header, that variable isn’t in scope for it. Variables cascade down in Blades, but not up:

// file.blade.php
<?php $variable = 'some value'; ?>
{{ $variable }} // 'some value'
{{ $partial_variable }} // throws an "Undefined Variable" error


// partial.blade.php
<?php $partial_variable = 'a different value'; ?>
{{ $variable }} // 'some value'
{{ $partial_variable }} // 'a different value'

I can think of a couple ways you might address your issue:

  1. You’re already defining the function in your App controller, so why not simply make it a variable returned by the controller instead of a static method? i.e. public function nameOfFunction() which will then be available in all Blades as $name_of_function? (I’m assuming you’re using soberwp/controller–the process is different if this is a different version of Sage.) This would arguably be the “Roots way” of solving the problem.
  2. …Or define your variable in the scope “above” your header and footer, so that it’s available to both of them, i.e.:
// layout.blade.php or wheverever these partials are included
<?php $var = App::name_of_function(); ?>
1 Like

@alwaysblank That worked! Yes, it was the @include not working like include(). You helped me months ago as well on my original post when I started working with roots wp. Thanks for your help!!!

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.