-1

I would like to be able to instantiate a class using a class name stored in another class's property, and I want to do this with one line of code, as in the comments in the code below (and it should work on at least one recent version of PHP 5). Is this possible?

<?php

class Foo {

  public function doFoo() {

    echo "foo\n";

  }

}

class Bar {

  function __construct($className) {

    $this->className = $className;

  }

  public function doBar() {

    //INSTEAD OF THESE TWO LINES...
    //$className = $this->className;
    //$instance = new $className();

    //I WOULD LIKE THIS (OR SOME OTHER) ONE-LINER TO WORK:
    $instance = $this->className();

    $instance->doFoo();

  }

}

$bar = new Bar('Foo');
$bar->doBar();

EXPECTED OUTPUT:

foo
John Sonderson
  • 3,238
  • 6
  • 31
  • 45
  • 2
    You just forgot the keyword `new` e.g. `$instance = new $this->className();` (And as you want it this works from PHP version +5.0, see: http://3v4l.org/H3O7X) Your current code would be: `$instance = Foo();` which is just calling a function Foo – Rizier123 Feb 17 '15 at 01:02
  • 2
    Also before you ask the next 3 questions which are typos or wrong php version i only can recommend you a quick [google](http://itsfunny.org/wp-content/uploads/2013/02/How-I-fix-stuff-working-in-IT.jpg) and [SO search](http://stackoverflow.com/search) + a little bit of basic debugging with error reporting at the top of your file(s): `` Also don't forgot the help center: http://stackoverflow.com/help – Rizier123 Feb 17 '15 at 01:07
  • 2
    @Rizier123 You're on the ball today! Good work :D – Darren Feb 17 '15 at 01:12
  • 1
    @Darren I try my best, and every day a little bit better – Rizier123 Feb 17 '15 at 01:13
  • 1
    @Rizier123 You're doing great, keep it up! – Darren Feb 17 '15 at 01:13
  • OK, I've been getting some great answers today, don't think I'll ask anything more on this topic. Special thanks to @Rizier123 for keeping up all his good work. – John Sonderson Feb 17 '15 at 01:25

1 Answers1

-1

There is an obvious typo in the code which is calling a function instead of a constructor, and can be fixed as follows:

$instance = new $this->className();

That does the trick.

John Sonderson
  • 3,238
  • 6
  • 31
  • 45