简体   繁体   中英

include file with visibility scope

When we include files in PHP, they are somehow cached. 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 :

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

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")); , nor namespaces either gave no expected effect with a least of code...

Use require_once() and include_once() . They'll make PHP remember what files were included, and NOT include them again elsewhere in the code. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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