使用PHP include,您可以在包含的页面中定义包含页面吗?

时间:2012-04-05 20:01:29

标签: php

  

可能重复:
  get name of current PHP script in include file
  Can an included PHP file know where it was included from?

这个标题有意义吗? :)

您能否确定PHP放入<?php include 'SomeFile.php'; ?>的{​​{1}}页面,来自已包含的页面?

在“INCLUDED”页面中是否有基于抓取目标的if语句?

我甚至说这是对的吗?

全部谢谢!

解决方案:

PAGEMAIN1.php

<?php
$MAIN2 ='';
$MAIN1 = 'MAIN1';
include 'PAGE1.php';
include 'PAGE2.php';
include 'PAGE3.php';
include 'PAGE4.php';
?>

PAGEMAIN2.php

<?php
$MAIN1 ='';
$MAIN2 = 'MAIN2';
include 'PAGE1.php';
include 'PAGE2.php';
include 'PAGE3.php';
include 'PAGE4.php';
?>

page1.php中

<?php
$PAGE1 = 'PAGE1';
if($MAIN1 == 'MAIN1'){
    echo '(This is PAGE 1 being "INCLUDED" in MAIN 1)<br>';
    }
if($MAIN2 == 'MAIN2'){
    echo '(This is PAGE 1 being "INCLUDED" in MAIN 2)<br>';
    }
?>

使page2.php

<?php
$PAGE2 = 'PAGE2';
if($MAIN1 == 'MAIN1'){
    echo '(This is PAGE 2 being "INCLUDED" in MAIN 1)<br>';
    }
if($MAIN2 == 'MAIN2'){
    echo '(This is PAGE 2 being "INCLUDED" in MAIN 2)<br>';
    }
?>

PAGE3.php

<?php
$PAGE3 = 'PAGE3';
if($MAIN1 == 'MAIN1'){
    echo '(This is PAGE 3 being "INCLUDED" in MAIN 1)<br>';
    }
if($MAIN2 == 'MAIN2'){
    echo '(This is PAGE 3 being "INCLUDED" in MAIN 2)<br>';
    }
?>

PAGE4.php

<?php
$PAGE4 = 'PAGE4';
if($MAIN1 == 'MAIN1'){
    echo '(This is PAGE 4 being "INCLUDED" in MAIN 1)<br>';
    }
if($MAIN2 == 'MAIN2'){
    echo '(This is PAGE 4 being "INCLUDED" in MAIN 2)<br>';
    }
?>

输出来自PAGEMAIN1.php

(This is PAGE 1 being "INCLUDED" in MAIN 1)
(This is PAGE 2 being "INCLUDED" in MAIN 1)
(This is PAGE 3 being "INCLUDED" in MAIN 1)
(This is PAGE 4 being "INCLUDED" in MAIN 1)

输出来自PAGEMAIN2.php

(This is PAGE 1 being "INCLUDED" in MAIN 2)
(This is PAGE 2 being "INCLUDED" in MAIN 2)
(This is PAGE 3 being "INCLUDED" in MAIN 2)
(This is PAGE 4 being "INCLUDED" in MAIN 2)

以防你想知道。 ;)谢谢!

3 个答案:

答案 0 :(得分:2)

您可以做的是创建一个在包含子页面的所有页面中使用的全局变量。在子页面中,您可以检查您所在的页面。那有意义吗? ; - )

<强>第1页:

<?php
   $THISPAGE = "page1";
   include("subpage.php");
?>

<强>第2页:

<?php
   $THISPAGE = "page2";
   include("subpage.php");
?>

<强>子页面:

<?php
   if ($THISPAGE == "page1")
      ...
?>

答案 1 :(得分:1)

有一组magic constants可用于获取此类信息,但我认为它们不会涵盖您想要的内容。你是否喜欢这样的事情:

mainfile.php中:

<?php include('included.php'); ?>

included.php:

this page was included from <?php echo __PARENTFILE __ ?>

将输出

this page was included from mainfile.php

注意: PARENTFILE 不存在且不起作用。只是弄清楚这是否意味着OP意味着什么。

答案 2 :(得分:0)

回答代码示例转移到重复的问题:

<强> Can an included PHP file know where it was included from?

相关问题