开发者

Pass value to an include file in php

开发者 https://www.devze.com 2022-12-27 03:59 出处:网络
How do you pass a parameter into an include file? I tried the following but it doesn\'t work. include \"myfile.php?var=123\";

How do you pass a parameter into an include file? I tried the following but it doesn't work.

include "myfile.php?var=123";

and in myfile.php, I try to retrieve the parameter using $_GET["var"].

include "myfile.php?var=123"; will not work. PHP searches for a file with this exact name and does not parse the parameter

for that I also did this:

include "http://MyGreatSite.com/myfile.php?var=123";but开发者_运维技巧 it does not also work.

Any hints? Thanks.


Wrap the contents of the included file in a function (or functions). That way you can just do

include "myfile.php";
myFileFunction($var1, $var2);


quick and dirty

 $var = 123;
 include "myfile.php";

in myfile just use "$var"

The same but without global variables:

  function use_my_file($param) {
      $var = $param;
      include "myfile.php";
  }

Hold on, are you trying to include the result of myfile.php, not its php code? Consider the following then

  $var = 123;
  readfile("http://MyGreatSite.com/myfile.php?var=$var"); //requires allow_url_fopen=on in php.ini

virtual might also work


Create a function, that's what they are for:

included.php

<?php

function doFoo($param) {
    // do something with $param
}

file.php

<?php

require_once 'included.php';

doFoo('some argument');


Code in included files is executed in the same scope as the including file.

This:

// main.php
$var = 'a';
include 'inc.php';
echo $var;

// inc.php
$var = 'b';

Is for most intents and purposes exactly the same as:

// main.php
$var = 'a';
$var = 'b';
echo $var;
0

精彩评论

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

关注公众号