phpdebuggingnamespacesincludenamespace-organisation

How to include an almost identical file in a separate namespace (for debugging purposes)


I'm faced with the following PHP code problem:

At the moment my PHP code is not making use of any namespaces. I have made modifications to an include file foobarinc.php so that I now have the two versions foobarinc-v1.php (the old version) and foobarinc-v2.php (the new version). The include file has some functions (e.g. foo()) which is present in both files. At the moment foobarinc-v2.php has some bugs, so I need to debug my code with foo() from fooinc-v1.php (because at least I know it works) but I also need to call foo() from foobarinc-v2.php in other places. I don't want to change anything in the `foobarinc-v1.php file because I will be needing it as it is, but I would be willing to add a namespace to the file if necessary. Can I use PHP namespaces to achieve my purpose?

e.g. I would like to do:

main.php:

include("includes/foobarinc-v2.php");

function main() {

  hello(); // from main.php

  namespace myDebugNameSpace {

    include("includes/foobarinc-v2.php");

    $a = foo(); // foo() version 2

    outerNameSpace::bar($a); // bar() version 1

  }

  world(); // from main.php

  foo(); // foo() version 1

}

main();

How can I fix the above code to achieve my purpose?


Solution

  • What you need to do is to add in foobarinc-v1.php namespace as follows:

    namespace foobarinc1;
    

    foobarinc-v2.php almost the same:

    namespace foobarinc2;
    

    Main.php

    include 'foobarinc-v1.php'; 
    include 'foobarinc-v2.php';
    use foobarinc1;
    use foobarinc2;
    
    foobarinc1->foo();
    foobarinc2->foo();
    

    You can find more here: http://php.net/manual/pl/language.namespaces.php