2009-12-19 106 views
1

更改我的包含头后添加一个函数。它禁用了我的php回声用户名代码。PHP包含错误

所以从

HTP://example.com/register.php R =用户名

HTP://example.com/register.php R =

<?php 

function headertop($page) { 

include('header.php'); 

} 

headertop('members'); 

?> 

<div id="myaccount"> 

<p class="reflink" align="center">To refer others, use this link: <span class="textblue"> 
      <?php require ("config.php"); echo $url; ?>/register.php?r=<?php echo $row["username"]; ?> 
      </span></p> 
+0

标题是“PHP包含错误”。你问你为什么会收到关于包含文件的错误,或者包含文件? – kiamlaluno 2009-12-19 10:25:20

回答

2

我的猜测是行不通的,因为$row不在范围内。它在header.php中定义,它现在在headertop()的本地。

为什么你这样包括header.php呢?

+0

嗯,我正在尝试使用函数为每个页面声明一个id,所以我可以使用css来突出显示活动导航链接 – AskaGamer 2009-12-19 08:49:50

+0

当我将它放在导航css完美的函数中时,但是当我自己包含或外功能导航CSS不起作用,但用户名是 – AskaGamer 2009-12-19 08:51:25

+0

见http://docs.php.net/language.variables.scope – VolkerK 2009-12-19 08:54:21

1

如果$row是在header.php文件的函数定义,尝试添加

global $row 

而且,它可能是更好的形式只是有你所有的包括在同一个地方。你可能不应该把它放在一个函数中。

+0

全局是邪恶的 – Gordon 2009-12-19 09:55:06

1

请考虑下面的代码,了解正在发生的事情:

<?php // bar.php 
    $one = 1; 
    $two = 2; 

<?php // foo.php 
    $someVar = 'var'; 

    function foo() 
    { 
     $someOtherVar = 'otherVar'; 
     include 'bar.php'; 

     // get defined vars in current scope 
     print_r(array_keys(get_defined_vars())); 
    } 

    foo(); 

    // get defined vars in current scope 
    print_r(array_keys(get_defined_vars())); 

将输出类似

Array 
(
    [0] => someOtherVar 
    [1] => one 
    [2] => two 
) 
Array 
(
    [0] => GLOBALS 
    [1] => _ENV 
    [2] => HTTP_ENV_VARS 
    [3] => argv 
    [4] => argc 
    [5] => _POST 
    [6] => HTTP_POST_VARS 
    [7] => _GET 
    [8] => HTTP_GET_VARS 
    [9] => _COOKIE 
    [10] => HTTP_COOKIE_VARS 
    [11] => _SERVER 
    [12] => HTTP_SERVER_VARS 
    [13] => _FILES 
    [14] => HTTP_POST_FILES 
    [15] => _REQUEST 
    [16] => someVar 
) 

正如你可以看到,在函数内部foo()的作用域,你可以访问bar.php中包含的变量,但是一旦该函数被执行和控制ol流回到全球范围,例如,在调用foo()之后,变量不可用,因为它们没有被导出到函数范围之外。如果您在功能范围外包含bar.php,例如

include 'bar.php'; // instead of foo() 
print_r(array_keys(get_defined_vars())); 

你会得到

Array 
( 
    ... 
    [16] => someVar 
    [17] => one 
    [18] => two 
) 

放置了很多变数为全球范围内承担污染全局范围和冒着变量名称冲突的危险。也就是说,一个包含文件可能有一个$ row变量,另一个可能也有一个变量,它们会相互覆盖。将属于一起的东西封装到类/对象中和/或用全局范围替换为Registry pattern更好。

虽然我非常喜欢面向对象的方法,但您仍然可以在适当的位置使用它。只需从函数调用中返回所需的变量即可。

function foo() 
    { 
     $someOtherVar = 'otherVar'; 
     include 'bar.php'; 

     // this is why I do not like this approach $one pops out all of a sudden. 
     // I can deduct, it has to be in bar.php, but if you do that often, your 
     // code will be very hard to read. 

     return $one; 
    } 

    $user = foo(); // will contain $one then 

    // get defined vars in current scope 
    print_r(array_keys(get_defined_vars())); 

    // gives 
    Array 
    (
     ... 
     [16] => someVar 
     [17] => user 
    ) 

当然,如果你想拥有在呼叫期间宣布到foo(所有变量),你就必须把它们放在一个数组,因为只有一个值可以在同一时间内返回。但是,这基本上是当你注意到它变得笨拙,切换到类感觉很自然(至少对我来说)。