开发者

include file with visibility scope

开发者 https://www.devze.com 2023-03-30 20:58 出处:网络
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\".

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?

E.g. 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_cont开发者_如何学编程ents("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.


Namespaces should fix this prob -> http://php.net/manual/en/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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号