los*_*sit 80 php parameters include
我必须根据某些条件从我的PHP脚本中显示一个页面.我有一个if条件,如果条件满足,我正在做"包含".
if(condition here){
include "myFile.php?id='$someVar'";
}
Run Code Online (Sandbox Code Playgroud)
现在问题是服务器有一个文件"myFile.php",但我想用一个参数(id)调用这个文件,"id"的值会随着每次调用而改变.
有人可以告诉我如何实现这一目标吗?谢谢.
Daf*_*aff 199
想象一下include是什么:复制并粘贴所包含的PHP文件的内容,然后将对其进行解释.根本没有范围更改,因此您仍然可以直接访问包含文件中的$ someVar(即使您可能会考虑基于类的结构,其中您将$ someVar作为参数传递或引用一些全局变量).
Pau*_*xon 44
你可以做这样的事情来达到你想要的效果:
$_GET['id']=$somevar;
include('myFile.php');
Run Code Online (Sandbox Code Playgroud)
但是,听起来你正在使用它包括某种函数调用(你提到用不同的参数重复调用它).
在这种情况下,为什么不把它变成常规函数,包含一次并多次调用?
Nic*_*las 25
包含就像代码插入一样.您在包含的代码中包含与基本代码中完全相同的变量.所以你可以在你的主文件中这样做:
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
Run Code Online (Sandbox Code Playgroud)
在"myFile.php"中:
<?
echo 'My id is : ' . $id . '!';
?>
Run Code Online (Sandbox Code Playgroud)
这将输出:
我的身份证是12345!
小智 8
最简单的方法是这样的
索引.php
<?php $active = 'home'; include 'second.php'; ?>
Run Code Online (Sandbox Code Playgroud)
第二个.php
<?php echo $active; ?>
Run Code Online (Sandbox Code Playgroud)
您可以共享变量,因为您使用“include”包含了 2 个文件
如果您要在PHP文件中手动编写此包含 - Daff的答案是完美的.
无论如何,如果你需要做最初的问题,这里有一个简单的小函数来实现:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
Run Code Online (Sandbox Code Playgroud)
?>
我经常使用这种变量构造.
| 归档时间: |
|
| 查看次数: |
145034 次 |
| 最近记录: |