0

Here is a method, in which a string is passed, using that string an instance is created. Example method:

public function action($actionType)
{
    //var_dump(new $actionType);

    if (!class_exists($actionType)) {
        //throw new Exception

    }

    if (!(new $actionType) instanceof ActionInterface) {
        ////throw new Exception
    }
    $actionType = new $actionType;
    echo $actionType->doAction();
}

But I am getting an error of class not found, however when I manually write the class name or manually append the namespace this way $actionType = __namespace__ . "\\$actionType";, then error goes. Why is that happening?

Harry
  • 1,282
  • 12
  • 17
  • 1
    Try to replace new $actionType; with new $actionType(); – Ivnhal Aug 21 '16 at 06:25
  • @stweb isn't creating an instance of a class without parentheses a short hand for not passing any parameters to the constructor? – rosengrenen Aug 21 '16 at 09:15
  • Also, I would put the `$actionType = new $actionType;` between the if statements to avoid creating two instances. In the last if-statement you would do: `if (!$actionType instanceof ActionInterface) { }` – rosengrenen Aug 21 '16 at 09:19
  • @harry123 are you using some kind of autoloading? – rosengrenen Aug 21 '16 at 09:20
  • Replace if (!$actionType instanceof ActionInterface) with if (!($actionType instanceof ActionInterface)). About parentheses, I agree wuth @Rasmus Rosengren, you can skip it. – Ivnhal Aug 21 '16 at 09:51
  • I suspect that PHP does not add default namespaces when processing variables in commands like 'new'. maybe interesting? [instantiate a class from a variable in PHP?](http://stackoverflow.com/questions/534159/instantiate-a-class-from-a-variable-in-php). Useful: manual: [Namespaces and dynamic language features](http://php.net/manual/en/language.namespaces.dynamic.php) . – Ryan Vincent Aug 21 '16 at 10:47
  • @harry123 could you please show us your project structure and what the files/class you are trying to load look like – rosengrenen Aug 21 '16 at 11:34
  • @RasmusRosengren yes, I am using Composer autoload class – Harry Aug 21 '16 at 16:25
  • Could you give us more information? – rosengrenen Aug 21 '16 at 16:41
  • Is the namespace static or dynamic? – Ivnhal Aug 21 '16 at 16:42
  • namespace of this class is something like this `namespace\subNamespace`, and folder structure is like this `app\namespace\subNamespace`, and from where I am loading the classes is index.php which is outside of the `app` directory. – Harry Aug 21 '16 at 16:54
  • Add more details to your question – rosengrenen Aug 21 '16 at 19:22

1 Answers1

0

Try this:

public function action($actionType) {
     //var_dump(new $actionType);
     if (!class_exists($actionType)) {
       //throw new Exception
     }
     $actionType = new $actionType;
     if (!($actionType instanceof ActionInterface)) {
        ////throw new Exception
     }

     echo $actionType->doAction();
}
Ivnhal
  • 1,099
  • 1
  • 12
  • 20