Classes – require conflict in constructor

I’m coding a WordPress plugin and I’m not sure regarding the function name conflict..

I have a file named test_handling.php which contains the following content :

Read More
function testing() { echo 'test'; }

I included this file in a class constructor (file named testcls.class.php) :

class TestCls {
   function __construct() {
      require_once('test_handling.php');

      testing();
   }

   function otherfunction() {
      testing();
   }

   // ...
}

In this case, I would like to know if the testing() function is only available in the TestCls class, or can it create conflicts if an other WP plugin has a function with the same name ?

Related posts

Leave a Reply

2 comments

  1. Even with the same name, the functions will have different scope if defined as class method. To make a call to a regular function you will do the following:

    testing();
    

    and the result will be:

    'test'
    

    the class method need an instance of the class or be statically called. To call the method class you will need the following formats:

    $class->test();
    

    or

    OtherPlugin::test();
    

    To sum up, the function test will be different if defined as class method. Then, you will not have conflicts.

    Other way to encapsulate your function and make sure you are using the right one is with namespaces. If you use a namespace in your test_handling.php

    <?php
    namespace myname;
    
    function testing(){echo 'test';}
    ?>
    

    You will access the function test like this:

    <?php 
    require_once "test_handling.php";
    
    use myname;
    
    echo mynametesting();
    

    Now you are sure about the function you are calling.

  2. When a file is included, the code it contains inherits the variable
    scope of the line on which the include occurs. Any variables available
    at that line in the calling file will be available within the called
    file, from that point forward. However, all functions and classes
    defined in the included file have the global scope
    .

    from include in PHP manual

    Which means that yes, you can have conflicts.