tags:

views:

41

answers:

5

I have a function that includes another file like so

// some function
function SomeFunction()
{
   $someData = 'SomeData';
   include_once('some_file.php');
}

// some_file.php
<?php echo $someData; ?>

How would I get this to work where the include file can use the variables from the calling function? I will be using some output buffering.

A: 

That's already available :)

See include()

Dor
+2  A: 

As long as $someData is defined in SomeFunction(), some_file.php will have access to $someData.

If you need access to variables outside of SomeFunction(), pass them as arguments to SomeFunction().

Jordan Ryan Moore
Does it have to be directly related? I am using a `_include_once` which extends the input `include_once` for a directory offset.
Daniel A. White
A: 

The best would be to not do use globals at all, but pass the variable as parameter:

function SomeFunction()
{
   $someData = 'SomeData';
   include_once('some_file.php');
   some_foo($someData);
}

Otherwise you risk transforming your code base in spaghetty code, at least on the long term.

Flavius
I really don't want to do this. I am constructing a simple view engine.
Daniel A. White
you mean a template system like smarty, but simpler? If yes, I'd have the right solution for you.
Flavius
A: 

Seems kinda unorganized to include files in functions...what about...

function SomeFunction()
{
   $someData = 'SomeData';
   return $someData;
}

$data = SomeFunction();
<?php include('file.php') ?> // file.php can now use $data
Galen
A: 

You don't have to do anything. Usage of include() (and it's siblings) is analogous to copy-pasting the code from the included file into the including file at the spot where include() is called.

Simple example

test.php

<?php

$foo = 'bar';

function test()
{
  $bar = 'baz';
  include 'test2.php';
}

test();

test2.php

<?php
echo '<pre>', print_r( get_defined_vars(), 1 ), '</pre>';

Again, this is analogous to the combined

<?php

$foo = 'bar';

function test()
{
  $bar = 'baz';
  echo '<pre>', print_r( get_defined_vars(), 1 ), '</pre>';
}

test();
Peter Bailey