Using PHP namespaces in included files

Viewed 596

I try to use namespaces with included files:

<?php
  namespace MyNamespace;

  function foo() {
    echo 'Test';
  }

  include( 'otherfile.php' );
?>

Inside otherfile.php is a <?php foo(); ?>; and I would like too see "Test" as output of it.

Is there any chance to realize that, without modifying that other file?

My wish: I would like to replace an existing file inside the code of an external library. I don't want to modify that code, since I expect to get further updates there.

1 Answers

No, it's not possible. You're defining the function MyNamespace\foo. The included file is calling the function foo. There's no way to change the meaning of what foo() refers to without altering the code in that file. If you want to replace the function foo, your only real hope is to define your own function foo (no namespace) and avoid loading the other implementation of that function. If not this, it's things like runkit, which you don't really want to have to resort to.

Related