-2

I have a variable called $name in my atlas.php file. I then have another php file called display.php where I want to print out the value of $name what was established in the other file.

The research I did led me to include, but when I do

include 'atlas.php';

in my display.php file, it displays all of the work that is inside of atlas.php. I simply want access to the variable, how would I do that?

  • 2
    Possible duplicate of [PHP, getting variable from another php-file](https://stackoverflow.com/questions/13135131/php-getting-variable-from-another-php-file) – Lucas Arbex Oct 11 '19 at 14:52
  • check [How to access a variable across two files](https://stackoverflow.com/questions/18588972/how-to-access-a-variable-across-two-files) – anehme Oct 11 '19 at 14:54
  • @LucasArbex This is still confusing me as to why it is displaying all of the stuff from atlas.php when I do include – Kaitlyn Wheeler Oct 11 '19 at 15:02
  • @KaitlynWheeler take a look at the [official documentation](https://www.php.net/manual/en/function.include.php). It has an extensible explanation about the subject. – Lucas Arbex Oct 11 '19 at 15:06

1 Answers1

0

Consider I have one Php file that sets a var and has the side effect of echoing out that variable.

<?php

$greeting = "hello earth";
echo $greeting;

Let's call that file greeting.php.

In another file, I could use a function to restrict scope. I could suppress output, and return the contents of the desired variable.

<?php
function get_greeting() {
    ob_start();
    include_once 'greeting.php';
    ob_end_clean();

    return $greeting;
}

$greeting = get_greeting();
var_dump($greeting);

This will output:

string(11) "hello earth" 

However, I don't think I've ever used anything like it practically, but that's not to say there is never a need. Be wary of other possible side effects.

Progrock
  • 7,373
  • 1
  • 19
  • 25