Skip to content
Advertisement

Alias inexistent class names in php

Consider the following code:

 use ReplacementClass;

 class A extends ReplacementClass {

 }

The ReplacementClass name in this code should only be a placeholder, an undefined, inexistent class. At runtime, or before runtime, I would like to alias this inexistent class, with a dynamically set existing class, for my code to work. Is there any way in PHP to do this?

Why I would like to achieve this, is that A defined in the above example, is a class in a project plugin, which I would like to make portable, so is ReplacementClass in the original plugin. I would like to keep an option for the team, to extend on these classes, and add new functionalities to them, which are only needed in the specific project that they are working on.

In the above situation, if both of those are real classes, I could extend a B class with A, and add the new functionalities in B, and I could also extend ReplacementClassSpecific with ReplacementClass and add new functionalities to it, but given the single inheritance of PHP, I couldn’t extend both.

Advertisement

Answer

One way you could do this is with class_exists, and adding a dummy placeholder if it doesn’t exist.

But ideally I’d suggest you look into Facades like Laravel uses. This way you can be flexible with implementations, without relying on inheritance.

see it online https://ideone.com/pWf8QU

/* // unhide this to see the two behaviours
  class ReplacementClass {
    public function foo() {
        return "foo";
    }
    public function bar() {
        return "bar";
    }
}*/
if(!class_exists('ReplacementClass')) {
   class MyReplacementClass {
     public function foo() {
        echo " foo does not exist, this is a placeholder";
     }
     public function bar() {
        echo " bar does not exist, this is a placeholder";
     }
   }
}
else {
   class MyReplacementClass extends ReplacementClass {
   }
}

class FooBar extends MyReplacementClass {

}

$x = new FooBar();
echo $x->foo() . $x->bar() . "n";
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement