开发者

Inside function variables to be used in includes in PHP

I have a function that includes another file like so

// some function
function Som开发者_如何学编程eFunction()
{
   $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.


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().


That's already available :)

See include()


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.


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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜