简体   繁体   English

包含可见范围的文件

[英]include file with visibility scope

When we include files in PHP, they are somehow cached. 当我们在PHP中包含文件时,它们会以某种方式进行缓存。 So, if one contains a class definition, when we try to include it twice, we will get an error saying "Can not redeclare class". 因此,如果其中包含一个类定义,则当我们尝试将其包含两次时,将收到一条错误消息:“无法重新声明类”。

But is it possible to get include file code invoked with a scope set to current function, let's say? 但是,是否有可能在范围设置为当前函数的情况下调用包含文件代码?

Eg if we have two files: 例如,如果我们有两个文件:

moo.php : moo.php

<?php
class Moo
{
  function __construct()
  {
    echo "hello, world!" . PHP_EOL;
  }
}
?>

main.php : main.php

<?php
function foo()
{
  include("moo.php");
  new Moo();
}

foo();

new Moo(); // <-- here should be an error saying "could not find class Moo"

include("moo.php");

new Moo(); // <-- and here should not
?>

As far as i've tried, not eval(file_get_contents("moo.php")); 据我所试,不是eval(file_get_contents("moo.php")); , nor namespaces either gave no expected effect with a least of code... ,命名空间也至少用最少的代码也没有产生预期的效果。

Use require_once() and include_once() . 使用require_once()include_once() They'll make PHP remember what files were included, and NOT include them again elsewhere in the code. 它们将使PHP记住所包含的文件,而不会在代码中的其他位置再次包含它们。 After the first include/require, subsequent ones on the same file will essentially become a null-op. 在第一个包含/要求之后,同一文件上的后续包含/替换基本上将变为空操作。

命名空间应解决此问题-> http://php.net/manual/zh/language.namespaces.php

You should try implementing autoload for your classes. 您应该尝试为类实现自动加载 It will help prevent things like this. 这将有助于防止此类情况。

Seems that monkey patching did the trick : 看来,猴子补丁的伎俩

<?php
$code = <<<EOS
namespace monkeypatch;

\$s = "moofoo";

echo "This should six, but is it?: " . strlen(\$s) . PHP_EOL;
echo "Whoa! And now it is six, right?: " . \strlen(\$s) . PHP_EOL;

function strlen(\$x) 
{
    return -3.14;
}
EOS;

eval($code);

echo "While out of namespaces it is still six...: " . strlen("moofoo") . PHP_EOL;

Lots of thanks to Marc B. for the hint! 非常感谢Marc B.的提示!

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

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