tags:

views:

146

answers:

2

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
function 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?

Thanks!

+1  A: 

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.

Pekka
Psst! Direct answer :-P
Col. Shrapnel
@Col I don't really understand what you mean?
Pekka
I am at war with direct answers, which SO encourages too much while most of time it's just a disservice to the OP, helping him with bad practice.
Col. Shrapnel
@Col how is my answer worse practice than the accepted answer? (Apart from the file_get_contents part which is fine and much preferable for passive data. But what if you do calculations in your include?)
Pekka
hell because file_get_contents is the only answer to the question "how to read comma separated from the file". Your answer is the perfect example to what I call "mindless direct answer".
Col. Shrapnel
@Col. I was focusing on the "how to work with return values from includes properly" aspect. Still, looking closely at the question, you are right. Anyway, as always, some more explanation would have helped this from the start.
Pekka
+5  A: 

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);
VoteyDisciple
baaah, thats exactly the same like that, i wanted to post :D
Nort
I don't really like fetching data from the include by declaring variables in it because you could be overwriting a variable in the namespace of the including script (no IDE will tell you if you are), and it's hard to tell in the code where the variable comes from.
Pekka
@VoteyDisciple Thanks! I made it a text file and used `file_get_contents()`. Slick!
letseatfood