Need a method to handle an argument with two possible types

In the following class, how would I type the component in “public function addComponent($component)” when I can’t determine the type until run time. In other words, I’d like it to be able to read in both an Foo Object and a Bar object and then have the logic of that method handle it.

Any suggestions?

class AwesomeClass
  Foo $K8s, $IPX;
  Bar $mte[];
                        // Right Here - Type?
  public function addComponent($component) : void
     if (type_of($component) == "Bar"){
      array_push( $mte, $component);
     }  elseif (type_of($component == "Foo" ) {
          if ( $component.getName() == "K8S" ) {
            $this->K8s = $component;
          } else if ( $component.getName() == "IPX" ){
              $this->IPX = $component;
          } else {

@cotton Would a “union” meet the need? That is a structure that can hold one of multiple types (e.g., either a foo or a bar) and “knows” which type is stored in it. If the restrictions on a union are too severe, you could write a similar “foobar” class with pointers to foo & bar, and a data member saying which is valid.

Wait… what language are you using? I was thinking C++, but on second look that seems doubtful.


Googling “php union type” turns up the fact that a recent or upcoming version of PHP will contain union types. There were also discussions of workarounds to get the equivalent in older versions. Stackoverflow “Is it possible to type hint more than one type?” seems promising - it discusses more than just type hinting.

Good luck in your search & design.

1 Like

In common practice I believe most developers would like to have Foo & Bar implement the same interface. Then you could do like so:

public function addComponent(FooBarInterface $component) : void
// add the component

This may not work with your requirements but is ideal with the current meta, since all classes implementing the interface have a common set of methods that all require the same arguments. This makes your AwesomeClass much simpler to implement since it doesn’t care about the details of each component type. Each implementation of FooBarInterface would handle any differences required for that implementation.