0

So I have the following 3 files:

index.php

<?php
    require("require/functions.php");
    $g = getGroup();
    var_dump($data);
    die();
?>

functions.php

<?php
    function getGroup(){
        if(condition) $g = 1;
        else if(another condition) $g = 2;
        else if...etc
        require("data/$g.php");
        return $g;
    }
?>

An example e.g. data/1.php file:

<?php
    $data = ["Some random data"];
?>

I tried various approaches like using global $data in index.php and various other things, but didn't have any luck using this approach

I could do it by changing the getGroup() function to getGroupAndData() and returning [$g, $data], however that isn't really ideal...

Likewise I also created a global variable $temp in functions.php, used $temp = $data, then could use global $temp in the index.php file

My current preferred method is just to use $GLOBALS['data'] = $data inside the getGroup(), function, though I'm curious, is there anyway I can access this $data array from within the index.php file without having to use these workarounds?

Thanks

  • Just declare `global $data` at the top of your function (inside it) – Rylee May 06 '22 at 06:38
  • 1
    That will get it to work, however it seems to be a roundabout way of doing it. The approach you said that was not ideal (`getGroupAndData`) looks to be a far better and more readable approach that is consistent across varying scopes – Rylee May 06 '22 at 06:40
  • This is a crazy approach. Stop it right away. – nice_dev May 06 '22 at 07:17

0 Answers0