简体   繁体   English

PHP 5.4忽略include中的define()?

[英]php 5.4 ignoring defined() in includes?

Not sure if this is due to a module I have installed or not, I've tried to remove all the extensions I have but this still doesn't work: 不知道这是否是由于我已安装的模块引起的,我试图删除我拥有的所有扩展名,但这仍然行不通:

//test1.php
if(defined("TEST1")) {
        return;
}
define("TEST1",1);
function test() {}

//test2.php
if(defined("TEST1")) {
        return;
}
define("TEST1",1);
function test() {}

//test.php
include_once('test1.php');
include_once('test2.php');
test();

Results in a duplicate definition error. 导致重复定义错误。 It looks like other checks like function_exists will work, but it's a bit messier to use. 看起来像function_exists这样的其他检查也可以使用,但是使用起来有点麻烦。

According to PHP documentation ( http://php.net/manual/en/functions.user-defined.php ): 根据PHP文档( http://php.net/manual/zh/functions.user-defined.php ):

Functions need not be defined before they are referenced, except when a function is conditionally defined 在引用函数之前无需定义它们,除非有条件地定义了函数

It means that if you don't put your test() function into conditional statement it will be defined BEFORE script execution start. 这意味着,如果不将test()函数放入条件语句中,则会在脚本执行开始之前进行定义。

To allow referencing functions that are defined further in the code, PHP at first searches the file for function (classes, etc) definitions, then runs the code. 为了允许引用代码中进一步定义的函数,PHP首先在文件中搜索函数(类等)定义,然后运行代码。 So when you're doing your: 因此,当您执行以下操作时:

if(defined('TEST1')) return;

Te function already exists and dupplicate error is triggered. 该功能已存在,并且触发了重复错误。 The solution is to put them in any conditional statement (it does not have to make sense) or even just in braces. 解决方案是将它们放在任何条件语句中(不必说得通),甚至可以放在括号中。 Functions defined in that manner will not be defined before script execution and also you won't be able to use them befere they are defined. 以这种方式定义的函数不会在脚本执行之前定义,并且在定义它们之后,您将无法使用它们。 You can fix your code just by doing this: 您可以通过执行以下操作来修复代码:

//test1.php
if(defined("TEST1")) {
        return;
}
define("TEST1",1);

{
    function test() {}
}

//test2.php
if(defined("TEST1")) {
        return;
}
define("TEST1",1);

{
    function test() {}
}

//test.php
include_once('test1.php');
include_once('test2.php');

test();

To test the behavior you can play with that two code snippets. 要测试行为,您可以使用这两个代码段。 This one will work: 这将工作:

<?php

test();

function test() {
    echo 'Hello world!';
}

But this will fail with undefined function: 但这将因未定义的函数而失败:

<?php

test();

{
    function test() {
        echo 'Hello world!';
    }
}

While this again will work: 虽然这将再次起作用:

<?php

{
    function test() {
        echo 'Hello world!';
    }
}

test();

Try 尝试

//test1.php
if(!defined("TEST1")) {
  define("TEST1",1);
  function test() {}
}

//test2.php
if(!defined("TEST1")) {
  define("TEST1",1);
  function test() {}
}

//test.php
include_once('test1.php');
include_once('test2.php');
test();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM