0

I am trying to build 2 separate custom plugins for my website when I run into this problem. Both of them are sharing the same kind of a scope, meaning I can't declare a new constant or function with the same name. Is this a known problem and you just have to add prefix? Or is there a better way to move around this?

Thanks

1

In PHP, constants are global so they have no scope. Per the PHP Manual:

Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope.

There is an exception to this if you are using a PHP Class. You can then tie the constant to that class.

class My_Class
{
    const BLAH = 'This is a Constant';
{
print My_Class::BLAH

As for functions they, like constants, are global as well. Per the PHP Manual:

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

For example, if I have:

function my_func() {
    function my_other_func() {
        // Code
    }

    // More Code
}

I can call my_other_func() on its own even though it is being defined within my_func().

You can again skirt this using a PHP Class:

class My_Class
{
   public function echo_hello_world() {
       $this->echo_hello();
       $this->echo_world();
   }

   private function echo_hello() {
       echo 'Hello ';
   }

   private function echo_world() {
       echo 'World!';
   }
}

$testObj = new My_Class();

$testObj->echo_hello_world();

However, if classes are overkill, your best bet is to simply namespace everything by appending something unique in front of the names you are currently using. Usually I will append the textdomain I defined for the plugin/theme so my_function() becomes textdomain_my_function().

| improve this answer | |
  • I am working my way between switching to OOP or just stick with procedural programming. Might be a good chance to jump over. – Tree Nguyen Jul 19 '17 at 0:40
  • I'm in the same boat. I started writing a plugin using procedural programming and it's getting way out of hand so I'm looking to flip it to OOP myself. But anything outside a Class needs to be namespaced though. – Cedon Jul 19 '17 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.