开发者

Include PHP file content as argument to function that expects string value?

Is it possible to include a file that contains a string value (in this case a comma delimited list of values) as an argument to a function?

For example:

include.php

<?php
'value1,value2,value3'
?>

function.php

<?php
fu开发者_开发问答nction test($string)
{
    echo $string;
}

test(include 'include.php');
?>

I've tried this and it doesn't work, but is there a way to do what I am trying?


Does include.php have to be a PHP file?

If not, make it an ordinary text file (eliminating the <?php and ?> tags), and use:

test(file_get_contents('include.txt'));

That will just read the contents of include.txt as a string, and of course you can then do whatever you'd like.

Otherwise, using include actually executes the PHP in the file, so you could make include.php contain:

$variable = 'value1,value2,value3';

And then use:

include('include.php');
test($variable);


include.php

<?php
 return 'value1,value2,value3';
?>

Reference: Manual on include() (Starting at Example #4)

If you have to work with include(), having this way is better than defining a variable in the include IMO, because the data flow is more understandable in the code. When defining arbitrary variables within the include, there is always the risk of overwriting a variable in the namespace of the including script.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜